to_string(x)和stoi(s)
#include <bits/stdc++.h>
using namespace std;
int main()
{
// string m = "423";
// cout << m << endl;
// int res = m-'0';//这样写是不对的,会报错,跑不成
// cout << res;
char c = '8';//c的范围只能是0-9 ,不能是两位数和两位数以上的数
int ans = c-'0';
cout << ans;
//那么多位数,怎么转换为字符串?答案: to_string(x) //注意横杠
int x = 131414;
string s = to_string(x);
cout << "反转前" << s << endl;
reverse(s.begin(),s.end());
cout <<"反转后"<< s << endl;
// cout <<"反转后" << reverse(s.begin(),s.end()) << endl;
// 这样写是不对的, reverse返回不是一个字符串
}
那么一个比较长的字符串, 比如12313, 456这种怎么转化为数字?有没有对应的c++函数
根据前面的分析不难写出
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s = "6782";
int n = s.size();
cout << n <<endl;
int res = 0 ;
for(int i = 0; i < n ; i ++)
{
res+=(s[i]-'0')*pow(10,n-i-1);
// cout <<res << endl;
}
cout << res << endl;
}
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s = "6782";
int ans = stoi(s);//字符串转数字函数
cout << ans << endl;
cout << typeid(s).name() << endl;//注意name后有一个小括号
cout << typeid(ans).name()<<endl;
double a = 123.12;
float b = 56.33;
cout << typeid(a).name() << " " << typeid(b).name() << endl;
}
学到c++的stoi函数了吗? 还有判断类型的函数,同理可以有stod, stof,stoll, to后面就是数据类型,d代表double,f代表float,ll代表long long ;
练习一个题
反序数指整数各位取反之后的数。如321 的反序是123,147 的反序是741,现输入n组a,b(ab均大于0且小于10000),如果a、b反转的和等于和的反转,则输出a、b.
例如: a=123, b=456, 那么a+b的和= 123+456=579.
#include <bits/stdc++.h>
using namespace std;
int Rev(int x)
{
string s = to_string(x);
reverse(s.begin(),s.end());
int res = stoi(s);
return res;
}
int main()
{
int a, b;
cin >> a >> b;
int res1 = Rev(a)+Rev(b);
int res2 = a+b;
if(Rev(res1) ==res2) cout << "YES" << endl;
else cout << "No" << endl;
}
太爱这个函数了, 自动去前面的0
最后一步咱们想一下暴力怎么求解,这样可以不受语言函数的限制,万一你哪一天学了java,哈哈哈
int Rev(int x)
{
int res = 0;
if(x < 0) {
return 0;
}
while(x>0){
res = res*10+x%10;
x/=10;
}
return res;//这个函数也是能去前0
}