gpt4 book ai didi

c++ - 我的 “stoi”函数或编译器有问题吗?

转载 作者:行者123 更新时间:2023-12-01 15:12:20 37 4
gpt4 key购买 nike

我尝试编写一个将数字字符串转换为整数的函数。使用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 ,所以我在 r函数中指出了 myStoi的值:
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';
}

关于c++ - 我的 “stoi”函数或编译器有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63752833/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com