数学四舍五入不正确

Rounding from math.h incorrect

本文关键字:不正确 四舍五入      更新时间:2023-10-16

我正在使用代码abbey上的任务来完成C++。我试图通过导入math.h来使用舍入函数,它适用于我试图输入的除一对之外的每一个值当我把4991264除以4并四舍五入时,它输出的答案是1.24782e+06

 #include <iostream>
#include <math.h>
using namespace std;
int getTotal(){
int total;
cin >> total;
return total;
}
void doMath(int total){
    int count;
    double holder;
    double holder2;
    double solution;
    solution = 0;
    count = 0;
    while (count != total){
        cout << "enter a number ";
        cin >> holder;
        cout << "enter a number ";
        cin >> holder2;
        solution = (holder / holder2);
        cout << round(solution) << "n";
        ++count;
}
}
int main(){
int total = getTotal();
doMath(total);

return 0;
}

http://ideone.com/f40E1s是代码和输入。

谢谢,

浮点变量保持给定类型的值(在内存中)
这个值以二进制格式以其自身的精度"停留"在那里
当必须以某种方式显示此值或输出时,通常会转换为十进制格式。这种转换有时会失去精度。

无论如何,当你进行精确的算术运算时,就像你的例子一样,通常情况下,转换为十进制不是问题
这里必须理解的是,"打印"一个值与"显示内存中的确切值"不同。

对象cout具有预定义的方式来显示您正在计算的值
确切的值没有改变,在这种情况下,这不是计算不好的问题
实际上,只是如何在屏幕上显示这个值的问题

用于打印值的格式为:,采用指数表示法,精度为"仅"6位小数位数

打印时需要提高值的精度,并避免使用指数表示法。

看看这个网站:C++中的输出格式

因此,例如,以下代码完成了这项工作(精度为8位小数):

  cout << setiosflags(ios::fixed) << setprecision(8) << round(solution) << "n";

一般来说,您必须研究并练习更多有关此格式选项的内容。