我有这个代码:
#include <iostream>
int main() {
long l1 = std::stol("4.2e+7");
long l2 = std::stol("3E+7");
long l3 = 3E7;
printf("%d\n%d\n%d\n", l1, l2, l3);
return 0;
}
预期输出为 42000000, 3000000, 3000000
但实际输出为(在 ideone C++14 和 VS2013 上测试):
4
3
30000000
为什么会这样,并且无论如何都要让 std::stol
考虑科学记数法?
最佳答案
您要查找的函数是 std::stof
而不是 std::stol
。 std::stof
在后台调用 std::strtod
,它支持科学记数法。但是,std::stol
在后台调用了 std::strtol
,但实际上并没有。
#include <iostream>
#include <string>
int main() {
long l1 = std::stof("4.2e+7");
long l2 = std::stof("3E+7");
long l3 = 3E7;
std::cout << l1 << "\n" << l2 << "\n" << l3;
return 0;
}
输出:
42000000
30000000
30000000
关于c++ - 为什么 std::stol 不能使用科学记数法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28696405/