第一次审题不当忘记考虑此题目因为数字超大,浪费了一些时间...
上代码!只要数字不是太大也是可以实现的
long long a = 0;
int temp = 0;
int total = 0;
int total2 = 0;
int w=0;
cin >> a;
while (a != 0) {
temp = a % 10;
total = total + temp;
a = a / 10;
}
total2 = total;
cout << total2 << endl;
while (total!=0)
{
w++;
total /= 10;
}
cout << w << endl;
while(w!=0) {
int t = 0;
if (w == 1) t = total2 % 10;
else t = total2 / pow(10, w - 1);
switch (t)
{
case 0:
cout << "ling" << " ";break;
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;
default:cout << "no" << " ";
break;
}
w --;
}
很容易发现这样做效率实在太低(可能是我的问题?)所以要用另一种方法来实现了。
用字符串的知识操作(这里我参考了柳神的思路)
简单说明一下就是因为数字太大就转换为字符串先将字符串转成数字相加得到一个结果然后重新在转换为字符串最后利用一个数组相对应的输出即可 简单粗暴 而且代码量是大大减少了
上代码!
string str[] = { "ling","yi","er","san","si","wu","liu", "qi","ba","jiu" };
for (int i = 0; i < s.length(); i++) {
total = total + (s[i] - '0');
}
string s2 = to_string(total);
for(int j = 0;j < s2.length();j++) {
if (j!=0)
{
cout << " ";
}
cout << str[(s2[j]-'0')];
}
total是这串数字所有相加的和在把total转换成字符串。s是用户输入的数字(用字符串表示)