[英]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.