PAT甲级A1005答案(使用C语言)

题目描述:

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

对题目的简单总结:

题目的要求实际上很简单,总共可以分为两步
1.输入一个数字并按位数求和;
2.将上述所求的和按位翻译为英文。

这里最关键的步骤是把一个数的每一位数分解出来
例如把 1234 ------> 1,2,3,4------->算出1+2+3+4的和

1234转化为1 2 3 4 的步骤为:

1.1234%10 得到 4
2.然后将1234自身变成1234/10
3.重复上述两步直到1234自身变为0

while(sum != 0){
		int j = sum % 10;
		str_sum[k] = j;
		sum = sum/10;
		k++;

有关C语言中字符串注意的点:
输入字符串:

char str[10000];  //用字符类型的数组代替字符串
scanf("%s", str); //注意这里str之前不用加引用符,因为这里的str已经代表第一个字符的地址 

字符串数组的定义(下面这两种方法都可以):

char res[10][10]={"zero","one","two","three","four","five","six","seven","eight","nine"};
char *res[] = {"zero","one","two","three","four","five","six","seven","eight","nine"};

答案代码:

#include
#include
#include

using namespace std;
char str[10000];  
int str_sum[1000000];
int sum = 0 ;
char res[10][10]={"zero","one","two","three","four","five","six","seven","eight","nine"};

int main(void){
    scanf("%s", str);  
	for(int i =0 ;i < 10000; i++){
		if(str[i]) {
			sum += (str[i] - '0');
		}
		
	}

	int k = 0;
	if(sum == 0) printf("%s", en_num[0]);//这是改正过程中加的语句
	while(sum != 0){
		int j = sum % 10;
		if(j != 0) str_sum[k] = j;
		sum = sum/10;
		k++;
	}
	for(k-=1; k >= 0; k--){
		printf("%s", res[str_sum[k]]);
		if(k!=0) printf(" ");
	}
    return 0;
}



你可能感兴趣的:(PAT,Advance,level)