为什么我输入的数字只读到6个有效数字

Why are the numbers I input only read to 6 significant figures?

本文关键字:6个 有效数字 只读 数字 输入 为什么      更新时间:2023-10-16

我正在尝试运行以下程序,它可以工作,但当我输入的值超过小数点后6位时,它会被四舍五入/截断,例如2.999999-->3。我如何设置它,使它停止执行此操作?

int main()
{
    double n=0, x=0; 
    while (cin >> n >> x) //will keep going until an integer is not entered
    {
       cout << "You entered the two integers " << x << " and " << n << endl;
       if (x-n <= (1.0/10000000) && n-x <= (1.0/10000000)) 
          cout << "The numbers are almost equal" << endl;
    }
return 0;
}

您可以使用std::setprecision:更改打印值的精度

cout << "You entered the two integers " << setprecision(20) << x
     << " and " << n << endl;

链接到ideone。