PAT甲级1005(C语言)

1005 Spell It Right (20 分)

Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English.

Input Specification:

Each input file contains one test case. Each case occupies one line which contains an N (≤10​100​​).

Output Specification:

For each test case, output in one line the digits of the sum in English words. There must be one space between two consecutive words, but no extra space at the end of a line.

Sample Input:

12345

Sample Output:

one five

 

来自

题目思路:

    题目要求读入一个非负整型数值,且数值小于等于10^100,故使用大小为100*int的数组存储数据。在读入数据时需要注意判断读入的数是否在0-9之间(如果是则存入,反之跳出循环)。因为数值最大值为9*100,所以可以用一个短整型sum来保存计算结果。最后通过sprintf()函数,将sum转换为一个字符数组便于处理单个数字(把0-9通过一个转换函数转换成所对应的英文字母)。

代码:

#include
#include
#define max 100
int main()
{
	void translator(char c);//转换函数
	int isnum(char num);//判断是否为数字。是返回1,否则返回0
 	int sum = 0, c = 0;
	int data[max];//存储读入的数据
	char s[4];//转换后的sum数据
	char num;
	scanf("%c", &num);
	for (int i = 0; i < max && isnum(num); ++i){
		data[i] = num-'0';
		++c;
		scanf("%c", &num);
	}
	for (int i = 0; i < c; ++i) {
		sum += data[i];
	}
	
	sprintf(s, "%d", sum);
	
	for (int i = 0; i < strlen(s); ++i) {
		translator(s[i]);
		if (i != (strlen(s)-1)) {
			printf(" ");
		}
	}
	return 0;
 } 
void translator(char c)
 {	
        if (c == '0') {
    	        printf("zero");
	}
 	else if (c == '1') {
 		printf("one");
 	}
 	else if (c == '2') {
 		printf("two");
 	}
 	else if (c == '3') {
 		printf("three");
 	}
 	else if (c == '4') {
 		printf("four");
 	}
 	else if (c == '5') {
 		printf("five");
 	}
 	else if (c == '6') {
 		printf("six");
 	}
 	else if (c == '7') {
 		printf("seven");
 	}
 	else if (c == '8') {
 		printf("eight");
 	}
 	else if (c == '9') {
 		printf("nine");
 	}

 }
 int isnum(char num) 
 {
 	int c = num-'0';
	if (c >= 0 && c <=9) {
		return 1;
	} 
	else {
		return 0;
	}
}

 

 

 

 

你可能感兴趣的:(PAT)