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<stdio.h>
#include<stdlib.h>
#include<string>

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



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值