c++ - 输入double变小了,没有明显的原因
问题描述
因此,当我输入像 12.45 这样的十进制数时,它会减少 0.00001 或导致我的函数无法正常工作的东西。
例如:如果 x 是 12.45,div 是 0.1,看 x 可以看到变成 12.449999999
但是如果 x 是 12.455 并且 div 是 0.01 它不会减少 x
double round(double x, double div){
if (div != 0){
double temp2 = 0;
int temp = x;
double dec = x - temp;
dec = dec/div;
temp = dec;
temp2 = dec-temp;
temp2 = temp2 * div;
cout << x << endl << endl;
if (temp2 >= div/2){
x+=(div-temp2);
}else{
x-=temp2;
}
cout << temp << " " << dec << " " << x << " " << temp2 << " " << div/2;
return x;
}else{
cout << "div cant be equal to zero" << endl;
}
}
我试图制作一个四舍五入的函数。我知道它可能不是最好的做法,但除了我之前描述的问题之外,它可以工作。
为了解决这个问题,我尝试在输入中限制小数位,但没有奏效。还尝试使用其他方法而不是使用双精度/整数组合而没有任何结果。
当 x 为 12.45 且 div 为 0.1 时,我希望输出为 12.5,但它不起作用,因为输入的 0.000001 丢失了。
解决方案
您的程序将被错过通知并且将无法运行。
这就是本标准中定义的编程语言中浮点值的处理方式。
https://en.wikipedia.org/wiki/IEEE_754#Basic_formats
由于操作的结果,它们通常需要四舍五入以适应它们的有限表示,从而使它们难以比较。
https://www.boost.org/doc/libs/1_36_0/libs/test/doc/html/utf/testing-tools/floating_point_comparison.html
您看到的问题是舍入误差的产物。
https://www.itu.dk/~sestoft/bachelor/IEEE754_article.pdf
推荐阅读
- azure-active-directory - Microsoft Graph API - 从 id 列表中获取目录对象 - 错误请求
- android - 使用 webview 时,html 自动重定向代码会起作用吗?
- android - 使用其他域帐户在 google play 开发者控制台中邀请新用户
- java - 不显示 TableView Javafx 的行
- php - 无需设备令牌或注册 ID 即可向 APP 发送推送通知
- php - PHP 表单验证不起作用,允许发送无效提交
- sql-server - 在 SQL Server DB 中使用架构时的注意事项
- mysql - 如何为具有重复结果输出的查询放置逗号分隔符?
- java - 如何从参数将元素添加到列表视图
- vb.net - 如何将特定列数据和行从数据库显示到excel?