gpt4 book ai didi

c++ - 四舍五入/截断双

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:15:16 26 4
gpt4 key购买 nike

我正在使用格式如下的财务数据进行计算:

<up to 5 digits>.<two digits>

基本上,在我的程序中我遇到了一个浮点错误。例如,如果我有:

11.09 - (11.09 * 0.005) = 11.03455

我希望能够使用 11.03455 而不是生成的内容:11.0345499999999...

我正在将我的程序生成的值与我在字符串格式的文本文件中的值进行比较。我只需要两个小数点的精度,我可以四舍五入。有什么办法可以将其削减到 11.03?

我想如果我把它变成一个字符串并逐个字符地解析它会是最简单的,只在'.'之后添加两个字符。特点。这是一个好的解决方案吗?有更好的想法吗?

这是我的:

string dataProcessor::createTwoDec(double price){
string s = to_string(price);
string output = "";
int dist = 0;
int num_wanted = 0;

bool pt_found = false;
for(int i = 0; i < s.length(); i++){
if(s[i] == '.')
pt_found = true;
if(pt_found)
dist++;
if(dist > 3)
break;
output += s[i];
num_wanted++;

}
return output.substr(0, num_wanted);
}

最佳答案

可以用下面的公式四舍五入到小数点后n位(n不要太大):

round(x*10^n)/10^n
where n is number of decimal places required.

在你的例子中,n 是 5。因此,它将是

 result = round(result*100000)/100000;

参见 How do you round off decimal places in C++?

关于c++ - 四舍五入/截断双,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34446856/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com