编写一个程序,从键盘上读入一个小于1000的正整数,然后创建并输出一个字符串,说明该整数的值。例如,输入941,程序产生的字符串是“Nine hundred and forty one”。
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
void split_number(int n, int* digits, int* count);
void split_number(int n, int* digits, int* count) {
int i = 0;
while (n > 0) {
digits[i++] = n % 10;
n /= 10;
}
*count = i;
}
int main() {
char unit_to_word[][6] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
char ten_to_word[][8] = { "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
int digits[4];
int count;
char strNum[100];
int num = 0;
printf("Please enter an integer less than 1000 and greater than 0\n ");
int result = scanf_s("%d",&num);
split_number(num, digits, &count);
if (count == 1) {
char* str = unit_to_word[digits[0]-1];
strcpy_s(strNum, str);
}
else if(count == 2)
{
char* str = ten_to_word[digits[1]-1];
strcpy_s(strNum, str);
strcat_s(strNum, " ");
if (digits[0] != 0) {
strcat_s(strNum, sizeof(strNum), unit_to_word[digits[0] - 1]);
}
}
else
{
char* str = unit_to_word[digits[2]-1];
strcpy_s(strNum, str);
strcat_s(strNum, " handred ");
if (digits[1] != 0) {
strcat_s(strNum, " and ");
strcat_s(strNum,sizeof(strNum), ten_to_word[digits[1] - 1]);
}
strcat_s(strNum, " ");
if (digits[0] != 0) {
strcat_s(strNum, sizeof(strNum), unit_to_word[digits[0] - 1]);
}
}
printf("The number you entered is converted to English is:\n %s\n\n", strNum);
return 0;
}