kk Exercise 6.1 Convert an integer to words

本文提供了一个C语言程序示例,该程序接收用户输入的一个小于1000的正整数,并将其转换为英文单词形式输出。程序通过定义不同数值范围内的字符串数组来实现整数到英文单词的映射。

Exercise 6-1. write a program that will prompt for and read a positive integer less than
1,000 from the keyboard, and then create and output a string that is the value of the
integer in words. For example, if 941 is entered, the program will create the string "Nine
hundred and forty one".

//
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <string.h>

int main(void)
{
  char *unit_words[] = {"zero", "one","two","three","four","five","six","seven","eight","nine"};
  char *teen_words[] = {"ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
  char *ten_words[] = {"error", "error","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
  
  
  //上面的是什么意思?
  
  char hundred[] = " hundred";
  char and[] = " and ";         //就是这个字符。 and字符串有5+1个字符,其中一个是结束字符。
  
  char value_str[50] = "";
  int value = 0;                     // Integer to be converted
  int digits[] = {0,0,0};            // 这是什么意思?digit这个数组里面有三个值?
  int i = 0;

  printf("Enter a positive integer less than 1000: ");
  scanf_s("%d",&value);
  if(value >= 1000)
    value = 999;
  else if(value < 1)
    value = 1;//为什么不直接显示错误,而要非执行这个区间的值

  while(value > 0)
  {
    digits[i++] = value % 10;//求得各位数!
    value /= 10;//十位以上的数字
  }

  if(digits[2] > 0)
  {
    strcat_s(value_str, sizeof(value_str), unit_words[digits[2]]);// unit_WORDS[digits[2]]这是什么意思?圆程序?
    strcat_s(value_str, sizeof(value_str), hundred);
    if(digits[1] > 0 || digits[0] > 0)
      strcat_s(value_str, sizeof(value_str), and);
  }
  if(digits[1] > 0)
  {
    if(digits[1] == 1)
      strcat_s(value_str, sizeof(value_str), teen_words[digits[0]]);
    else
    {
      strcat_s(value_str,sizeof(value_str), ten_words[digits[1]]);
      if(digits[0] > 0)
      {
        strcat_s(value_str, sizeof(value_str), " ");
        strcat_s(value_str, sizeof(value_str), unit_words[digits[0]]);
      }
    }
  }
  else
    if(digits[0] > 0)
      strcat_s(value_str, sizeof(value_str), unit_words[digits[0]]);
      
    //最终一步到位的输出,程序相当简洁,上面的构思巧妙
  printf("\n%s\n", value_str);
  return 0;
}

 

转载于:https://www.cnblogs.com/xiaomi5320/p/4190776.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值