【发布时间】:2018-09-01 15:28:45
【问题描述】:
当我调用我的函数时:
formatCurrency(7.5);
string formatCurrency(double cash) {
cout << "fmod(cash,.1) is equal to " << fmod(cash,.1) << endl;
if(fmod(cash,1) == 0) {
cout << cash << ".00";
}
else if(fmod(cash,.1) == 0.1) {
cout << cash << "0";
}
else if(fmod(cash,.01) == 0.01) {
cout << cash;
}
else{
cout << "Error: unable to display in currency format";
}
return "";
}
fmod(7.5,.1) 显然等于 .1,当我运行程序时它甚至会输出。但相反,我得到以下输出:
fmod(cash,.1) is equal to 0.1
Error: unable to display in currency format
什么给了?我认为我的代码没有任何问题。该代码确实适用于整数/第一个 if 语句,但任何带有小数的东西都会让事情变得冒险。
【问题讨论】:
-
您没有正确比较两个浮点值。比较它们的正确方法是检查它们的差异是否在某个
delta之内,其中delta表示您愿意为您的应用程序容忍的误差范围。原因是大多数浮点值不能用二进制精确表示。 -
据我所知,浮点类型的变量和文字不应该直接比较。
-
正如@MikeBorkland 所说,这也是您从不使用浮点数换取现金的原因之一。而是使用整数。
-
@MikeBorkland -- 比较浮点值是否相等的正确方法是比较它们是否相等。检查它们是否“几乎相等”会引入许多其他问题;这不是一个简单的替代品。
-
请注意,仅添加 epsilon 是不够的,浮点比较远不止于此。阅读Comparing Floating Point Numbers, 2012 Edition 和What is the most effective way for float and double comparison?
标签: c++ floating-point comparison