c++ - C++ String to Number 自定义函数问题
问题描述
我正在尝试在 C++ 中将字符串转换为数字(长双精度)。当小数点后的位数大于 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:\--path-->test.exe
-912.302
后来我发现:
如果在主函数中,我们通过 "-912.3016"
cout<< c2n("-912.3016") <<endl;
然后输出是:
D:\--path-->g++ -o test.exe test.cpp
D:\--path-->test.exe
-912.302
但是如果我们通过 "-912.3015"
cout << c2n("-912.3015") <<endl;
然后是o / p:
D:\--path-->g++ -o test.exe test.cpp
D:\--path-->test.exe
-912.301
我应该采取 double 而不是 long double 还是有其他问题?
解决方案
默认precision
值为std::cout
6,由 设置std::ios_base::init
。所以
auto val = 1234.56789;
std::cout<<val<<'\n`;
产生 1234.57 即 6 位数字(并相应地四舍五入)。从标题中相应地设置precision
使用,您应该能够看到正确的值。setprecision
iomanip
std::cout << std::setprecision(12) << c2n("-912.301956") << std::endl;
推荐阅读
- c - 任何人都可以向我解释以下内容
- r - 在 R 上的 Google 距离矩阵 API 中达到查询限制
- asp.net-core-mvc - 更新 ContextModelSnapshot EF Core
- javascript - 更改元素后,JavaScript (jQuery) 不再反应
- python - Python:需要高精度整数的解决方案(生成素数)
- javascript - 如何判断图像是否未在 Angular 中加载?
- json - 使用 JSON 和 TypeScript 进行静态类型化
- java - 返回类型与其所属名称相同的接口类型方法的用例场景是什么?
- c# - 在 .NET 中同步本地网络 NAS 上的文件
- javascript - 如何在 Firebase 快照中返回数据