欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-03-14 19:48:44
...

1.题目链接

https://pintia.cn/problem-sets/994805260223102976/problems/994805324509200384

2.题目分析

大体思路就是将各位数字相加,将和取余求出每一位的数,再将对应的中文字符串存入数组,最后输出

3.代码

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
using namespace std;
int main()
{
	string number;
	cin >> number;
	string list[101];
	int amount = 0;
	for (int i = 0; i < number.length(); i++)
	{
		amount += (number[i] - 48);
	}
	int copy = amount;
	int a = 10;
	int b = 1;
	int c = 0;
	while (amount)
	{
		int temp = amount % (int)pow(a, b);
		switch (temp)
		{
		case 0:list[c++] = "ling"; break;
		case 1:list[c++] = "yi"; break;
		case 2:list[c++] = "er"; break;
		case 3:list[c++] = "san"; break;
		case 4:list[c++] = "si"; break;
		case 5:list[c++] = "wu"; break;
		case 6:list[c++] = "liu"; break;
		case 7:list[c++] = "qi"; break;
		case 8:list[c++] = "ba"; break;
		case 9:list[c++] = "jiu"; break;
		}
		amount /= 10;
	}
	for (int i = c - 1; i >0; i--)
	{
		cout << list[i] << " ";
	}
	cout << list[0];

}

4.改进

之所以要将字符串先存入数组是因为不知道amount的位数是多少,无法从前向后求余

于是就将得出的amount先转换为字符串

5.代码

#include<iostream>
#include<sstream>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
int main()
{
	string number;
	cin >> number;
	string list[10] = {"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
	int amount = 0;
	for (int i = 0; i < number.length(); i++)
	{
		amount += (number[i] - 48);
	}
	string transamount;
	stringstream ss;
	ss << amount;
	ss >> transamount;
	int i = 0;
	for (; i < transamount.length()-1; i++)
	{
		cout << list[transamount[i] - '0']<<' ';
	}
	cout << list[transamount[i] - '0'];

}

6.附上string与int相互转换的方法

使用stringstream

(参考https://www.cnblogs.com/houchen/p/8984164.html

1.数字转换为字符串

#include <string>

  #include <sstream>

  int main(){
    double a = 123.32;
    string res;
    stringstream ss;          定义流ss
    ss << a;                       将数字a转化成流ss
    ss >> res;                    将流ss转化成字符串
    return 0;
  }

2.字符串转换为数字

#include <string>

  #include <sstream>

  int main(){
    double a ;
    string res= "123.32";
    stringstream ss;  
    ss << res;                  
    ss >> a;
    return 0;
  }

int 转string使用to_string函数

#include<iostream>
#include<string>
using namespace std;
int main()
{
	int n = 100;
	string ss = to_string(n);
	cout << ss;
}

如果是小数转换为字符串的话使用该方法会自动添加许多0

sprintf函数、sscanf函数

#include <iostream>
#include <string>
using namespace std;

int main()
{
	char str[10];
	int a = 1234321;
	//将整数转化为字符串
	sprintf(str, "%d", a);
	cout << str;
    char str1[10];


	double b = 123.321;
	//将浮点数转化为字符串
		sprintf(str1, "%.3lf", b);
	cout << str1;
}
#include <iostream>
#include <string>
using namespace std;

int main()
{
    char str[]="1234321";
    int a;
    sscanf(str,"%d",&a);//注意这里的&
    cout<<a<<endl;

    char str1[]="123.321";
    double b;
    sscanf(str1,"%lf",&b);
    cout<<b<<endl;
    return 0;
}