[英]Is there something wrong with my “stoi” function or my compiler?
我尝试编写一个函数将一串数字转换为整数。 当我使用 g++ 9.2.0 在 VS 代码上运行我的代码时,我得到了错误的输出,但是当我在 repl.it 上运行它时,我得到了正确的输出。 这是我的代码:
#include <iostream>
#include <cmath>
using namespace std;
int charToInt(char c)
{
return c - '0';
}
int myStoi(string s)
{
int r = 0, len = s.length();
for (int i = 0; i < len; i++)
{
r += charToInt(s[i]) * pow(10, len - i - 1);
}
return r;
}
int main()
{
string str = "123";
cout << stoi(str) << endl;
cout << myStoi(str) << endl;
return 0;
}
这是 VS 代码的输出:
PS C:\Users\ASUS\Code\Practice> g++ .\convertChartoInt.cpp
PS C:\Users\ASUS\Code\Practice> .\a.exe
123
122
这是 repl.it 上的输出:
./main
123
123
我试图弄清楚为什么我在 VS 代码上得到数字122 ,所以我在myStoi
函数中计算出r
值:
for (int i = 0; i < len; i++)
{
r += charToInt(s[i]) * pow(10, len - i - 1);
cout << r << " ";
}
结果如下:
PS C:\Users\ASUS\Code\Practice> .\a.exe
99 119 122
我认为第一个数字应该是100以生成正确的输出,但它返回99 ,谁能告诉我这个错误是什么以及如何修复它? 谢谢!
解决这个问题的通常方法是通过乘以 10 来累加结果:
for (int i = 0; i < len; ++i) {
r *= 10;
r += s[i] - '0';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.