c++ - 打印时缺少小数点

标签 c++

下面是我正在使用的一些简单代码:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    float f = 1.66f;
    int d = (int)f;
    double g = (double)d;
    cout.precision(6);
    cout<<g<<"\n";
}

我想让它打印 1.000000 但它只打印 1。但是,即使在将 int 升级为 double 之后,它不会自动将其转换为整数值吗?

最佳答案

您可以添加 cout << std::fixed;

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    float f = 1.66f;
    int d = (int)f;
    double g = (double)d;
    cout.precision(6);
    cout << std::fixed;
    cout<<g<<"\n";
}

然后你得到 1.000000

解释(编辑)

当您使用 std::fixed 时:

When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.

当您使用 std::defaultfloat (您正在使用的那个):

When floatfield is set to defaultfloat, floating-point values are written using the default notation: the representation uses as many meaningful digits as needed up to the stream's decimal precision (precision), counting both the digits before and after the decimal point (if any).

这就是为什么下面的 .000000被认为是无关紧要的!
(如果你有 1.00001 它就会被打印出来)

关于c++ - 打印时缺少小数点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31235336/

相关文章:

c++ - 几何着色器只创建一个图元

c++ - 在什么情况下使用 'const T*' 作为输入参数比 'const T&' 更可取?

c++ - 在单声道项目和 C++ 控制台应用程序之间传输数据?

c++ - 需要帮助使用 switch 语句创建函数和错误

c++ - 在不使用 __fastcall 的情况下 Hook __thiscall

c++ - 如何正确编译和链接 C 程序?

c++ - 代码 C++ 中的运行时错误

c++ - 当具有 std::map<int,std::ofstream> 成员时,类不从 dll 导出

c++ - 在 vector 中编写线程安全

c++ - 'list::list' 命名构造函数,而不是类型