(C++)1002 写出这个数

#include<cstdio>
#include<cstring>

const int M = 100;
//用字符数组装输入
//定义变量,输出字符数组的长度
//对字符数组遍历求和
//对结果逐位输出汉语拼音 

void hanzi(int i){
	
	switch(i){
		case 0:printf("ling");
				break;
		case 1:printf("yi");
				break;
		case 2:printf("er");
				break;
		case 3:printf("san");
				break;
		case 4:printf("si");
				break;
		case 5:printf("wu");
				break;
		case 6:printf("liu");
				break;
		case 7:printf("qi");
				break;
		case 8:printf("ba");
				break;
		case 9:printf("jiu");
	}
}

int main(){
	char str[M+1];
	scanf("%s",str);
	int length,sum=0,i;
	length = strlen(str);
	for(i=0;i<length;i++){
		sum += (str[i]-'0');
	}
	
	int bai = sum/100;
	if(bai!=0){
		hanzi(bai);
		printf(" ");
	}
	int shi = sum%100/10;
	if(shi!=0){
		hanzi(shi);
		printf(" ");
	}
	int ge = sum%10;
	hanzi(ge);
	printf("\n");
	
	
	
	
	return 0;
}

经验:如果用二位字符数组来表示数字和汉字的对应关系会使得代码更简洁,即

char transform[10][5]={"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
有transform[0]等于"ling"
上一篇:【PAT乙级】1002 写出这个数


下一篇:1002 写出这个数 (20 分) java解题