除以1000会舍入double var并丢失小数位

问题描述 投票:3回答:2
#include<iostream>
using namespace std;

int main()
{
    unsigned int x = 293125555;

    double y =  (double)x/1000.0;

    cout << y << endl;

    return 0;
}

我期望输出为293125.555,但我却得到293126。这是因为在内存中存储double的方式吗?

c++ double
2个回答
0
投票

提供有关库在其上编译的特定平台中算术类型(整数或浮点)的属性的信息。

std::setprecision中的[iomanip

设置用于格式化输出操作上的浮点值的十进制精度。

并在代码中使用它们:

#include <iostream> #include <iomanip> #include <limits> using namespace std; int main() { unsigned int x = 293125555; double y = (double)x/1000.0; cout << setprecision(numeric_limits<double>::digits10 + 1) << y << endl; return 0; }


0
投票
cout.precision(3);
© www.soinside.com 2019 - 2024. All rights reserved.