【问题标题】:Is there something wrong with my "stoi" function or my compiler?我的“stoi”函数或编译器有问题吗?
【发布时间】:2020-09-05 10:20:28
【问题描述】:

我尝试编写一个函数来将一串数字转换为整数。当我使用 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,谁能告诉我这个错误是什么以及如何修复它?谢谢!

【问题讨论】:

  • 无法复制godbolt.org/z/jvh47Y
  • pow 进行浮点运算,因此您可能会得到类似2.999999… 而不是3,当您将其转换为int 时,它不会四舍五入,但会成为2。这不是错误,而是在使用浮点运算时必须预料到的事情
  • @Sopel 无法复制它,并不意味着不会发生。
  • @t.niese 然而,这很奇怪,因为即使使用 -std=c++98 gcc 也会(错误地?)std::pow(int, int) 然后浮点乘法应该是准确的。我什至无法让 gcc 发出可能被破坏的代码。

标签: c++


【解决方案1】:

解决这个问题的常用方法是将结果乘以 10:

for (int i = 0; i < len; ++i) {
    r *= 10;
    r += s[i] - '0';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    相关资源
    最近更新 更多