【发布时间】:2016-05-02 12:43:48
【问题描述】:
通过以下简单的 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.
如何处理这个问题?编程中是否有规则可以在更复杂的情况下避免或控制此问题?
【问题讨论】:
-
将 FP 结果转换为整数可能会因截断而受到很大影响。建议四舍五入。
cents_v1 = round(price*100 - euro*100);
标签: c++ floating-point floating-accuracy associativity