PAT 1002. 写出这个数 (20)

读入一个自然数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 ;


欢迎大神指正讨论!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值