kk Exercise 6.1 Convert an integer to words

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;
}

 

posted @ 2014-12-28 22:49  稳稳稳稳稳稳  阅读(281)  评论(0编辑  收藏  举报