【发布时间】:2021-06-15 17:30:34
【问题描述】:
我正在尝试在 C++ 中将字符串转换为数字(long double)。当小数点后的位数大于3时会出现问题。它会自动将小数点后四舍五入到最接近的第三位。
附加信息:
- 编译器:mingw
- 操作系统:win10
这是代码(test.cpp):
#include<iostream>
#include <string>
#include <math.h>
using namespace std;
double long c2n(string n) {
double long num=0;
bool isdec = false, is_ve=false;
// is_ve checks if number is negative
// isdec checks if the decimal point is reached and numbers can be added after decimal
char c;
// to store the the character which needs to be checked
short i = 0, count=1;
if (n.at(0)=='-')
{
i=1;
is_ve=true;
}
for (; i < n.length(); ++i)
{
c=n.at(i);
if (c=='.'){
isdec=true;
continue;
}
if (!isdec)
num=num*10+(c-'0');
else{
num = num + (c-'0')/pow(10,count);
count++;
}
}
if (is_ve)
{
return -num;
}
return num;
}
int main(int argc, char const *argv[])
{
cout << c2n("-912.301956") << endl;
return 0;
}
这是输出:
D:\--path-->g++ -o test.exe test.cpp
D:\--路径-->test.exe
-912.302
后来发现的:
如果在主函数中,我们传递“-912.3016”
cout
然后输出结果是:
D:\--path-->g++ -o test.exe test.cpp
D:\--路径-->test.exe
-912.302
但是如果我们通过“-912.3015”
cout
然后是o/p:
D:\--path-->g++ -o test.exe test.cpp
D:\--路径-->test.exe
-912.301
我应该使用 double 而不是 long double 还是有其他问题?
【问题讨论】:
-
通过
==比较双打是有问题的,但是为了进行正确的测试,您可以编写一个将数字转换回字符串的函数,以查看您是否获得了原始字符串。即使通过cout将您当前的问题放在一边测试也不是那么可靠 -
btw
pow不是用整数调用的。无论如何,在循环索引为count的循环中调用pow(x,count)是浪费cpu 周期。在每个循环中累积*0.1要简单得多 -
试试
cout << -912.301956;,它也会打印-912.302。