PAT (Basic Level) Practice 1002 写出这个数 (20)

读入一个自然数n,计算其各位数字之和,用汉语拼音写出和的每一位数字。

1输入一个数
这个数非常巨大 ,所以不能用int或者double,此处用getchar()读取输入的数字。
getchar()会把输入的字符串一位一位读出来。

while ((c = getchar()) != '\n')
    {
        cout << c - '0' << endl;
        sum = sum + c-'0';  
        //把char中的数字转换为int并求和。
    }

输入:789
结果:
7
8
9

2如何把int sum中的数字一位一位读出来?
利用sprintf把int转换为char[],再利用条件char[i]!=0

sprintf(a, "%d", sum);//%d表示十进制
for (int i = 0; a[i] != 0; i++)
    {
        cout << a[i] << endl;
    }

结果:
2
4

3把数字转换为汉语拼音。

    switch (a[i] - '0')
        {
        case 1:
            cout << "yi";
            break;
        case 2:
            cout << "er";
            break;
        case 3:
            cout << "san";
            break;
        case 4:
            cout << "si";
            break;

        case 5:
            cout << "wu";
            break;
        case 6:
            cout << "liu";
            break;
        case 7:
            cout << "qi";
            break;

        case 8:
            cout << "ba";
            break;

        case 9:
            cout << "jiu";
            break;

        case 0:
            cout << "ling";
            break;

完成。

代码块

代码块语法遵循标准markdown代码,例如:

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>

using namespace std;
double x, y;
double m;
double d;
double z1;
char a[1000];
int sum;
char c;
char b[];

int main()
{
    while ((c = getchar()) != '\n')
    {
        sum = sum + c - '0';
    }
    sprintf(a, "%d", sum);
    for (int i = 0; a[i] != 0; i++)
    {
        switch (a[i] - '0')
        {
        case 1:
            cout << "yi ";
            break;
        case 2:
            cout << "er ";
            break;
        case 3:
            cout << "san ";
            break;
        case 4:
            cout << "si ";
            break;

        case 5:
            cout << "wu ";
            break;
        case 6:
            cout << "liu ";
            break;
        case 7:
            cout << "qi ";
            break;

        case 8:
            cout << "ba ";
            break;

        case 9:
            cout << "jiu ";
            break;

        case 0:
            cout << "ling ";
            break;
        }
    }

    return 0;



}
...
阅读更多

没有更多推荐了,返回首页