读入一个自然数n,计算其各位数字之和,用汉语拼音写出和的每一位数字。
输入格式:每个测试输入包含1个测试用例,即给出自然数n的值。这里保证n小于10100。
输出格式:在一行内输出n的各位数字之和的每一位,拼音数字间有1 空格,但一行中最后一个拼音数字后没有空格。
输入样例:1234567890987654321123456789输出样例:
yi san wu
思路:一个基本数据类型显然盛不下10^100这么大的数,所以,首先用一个string接收输入,然后转化成int数组,求出sum,最后case即可,代码如下:
#include"iostream"
#define max 100
#include<string>
#include"string.h"
using namespace std;
void getNum(int num[], string input)
{
int index = 99;
for (int j = 0;j<max;j++)
{
num[j] = 0;
}
for (int i = input.length() - 1;i >= 0;i--)
{
num[index] = stoi(input.substr(i, 1));
index--;
}
}
void output(int num)
{
switch (num) {
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:;
}
}
int main()
{
string input;
int num[100];
int sum = 0;
cin >> input;
getNum(num, input);
for (int i = 0;i<max;i++)
sum += num[i];
int first, second, third = 0;
first = sum / 100;
second = sum / 10 - first * 10;
third = sum - first * 100 - second * 10;
if (first != 0)
{
output(first);
cout << " ";
output(second);
cout << " ";
output(third);
}
else if (second != 0)
{
output(second);
cout << " ";
output(third);
}
else
{
output(third);
}
return 0;
}
用到两个函数,一个是substr();一个是stoi(),都在string头文件中。
学习补充:
stoi:string to int
#include <iostream>
#include <string>
int main()
{
std::string str1 = "45";
std::string str2 = "3.14159";
std::string str3 = "31337 with words";
std::string str4 = "words and 2";
int myint1 = std::stoi(str1);
int myint2 = std::stoi(str2);
int myint3 = std::stoi(str3);
// error: 'std::invalid_argument'
// int myint4 = std::stoi(str4);
std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n';
std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n';
std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n';
//std::cout << "std::stoi(\"" << str4 << "\") is " << myint4 << '\n';
}
Output:
std::stoi("45") is 45
std::stoi("3.14159") is 3
std::stoi("31337 with words") is 31337
stod:string to double
#include"iostream"
#include<string>
#include"string.h"
using namespace std;
int main()
{
string a = "3.101";
double aa = stod(a);
cout << aa;
return 0;
}
类似还有stol:string to long ;stoll:string to long long ;
欢迎大神指正讨论!