gpt4 book ai didi

c++ - 更改关联性时答案略有不同

转载 作者:搜寻专家 更新时间:2023-10-31 00:57:41 25 4
gpt4 key购买 nike

通过以下简单的 C++ 练习

#include <iostream>
using namespace std;
int main()
{
int euro, cents_v1, cents_v2, do_again;
double price;

do_again = 1;

while(do_again != 0){

cout<<"Insert price in Euro with cents"<<endl;
cin>>price;

euro = price;
cents_v1 = price*100 - euro*100;
cents_v2 = (price - euro) * 100;

cout<<"Total: "<<euro<<" euro and "<<cents_v1<<" cents"<< endl;
cout<<"Total: "<<euro<<" euro and "<<cents_v2<<" cents"<< endl;

cout <<"\nDo it again? 1: yes, 0: no."<<endl;
cin>>do_again;

}
return 0;

}

你可以得到两个不同的答案,如果输入是,例如 31.13:

Insert price in Euro with cents
31.13
Total: 31 euro and 13 cents
Total: 31 euro and 12 cents

Do it again? 1: yes, 0: no.

如何处理这个问题?在更复杂的情况下,编程中是否有避免或控制此问题的规则?

最佳答案

浮点加法和乘法是可交换的,但不是结合的或分配的。因此,正如您所观察到的,cents_v1cents_v2 实际上可能代表不同的值。

避免这些类型的浮点陷阱的一种通用技术是使用任意精度的算术库。有quite a few of these ,而且我对它们还不够熟悉,无法推荐其中一个。当然,使用任意精度数字会导致性能下降,但在您知道您的算法是瓶颈之前,进一步优化是不明智的。

如果您绝对必须使用浮点运算,可以使用多种经验法则来提高长浮点计算的准确性;查看一些数值方法文本以获取更多信息。还有大量关于浮点计算精度的研究,产生了一些 rather cool software .

关于c++ - 更改关联性时答案略有不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36985005/

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