如何输出计算到小数点后两位的中间器?

How to output an interger which is calculated to two decimal places?

本文关键字:两位 中间 小数点 何输出 输出 计算      更新时间:2023-10-16

很容易输出一个双精度值,该值计算到小数点后两位。 代码片段如下:

cout.setf(ios_base::showpoint);
cout.setf(ios_base::fixed, ios_base::floatfield);
cout.precision(2);
cout << 10000000.2 << endl;       // output: 10000000.20
cout << 2.561452 << endl;         // output: 2.56
cout << 24 << endl;               // output: 24         but I want 24.00, how to change my code?

如何输出计算到小数点后两位的中间器?我想要 24.00 作为输出。

这取决于你的 24 是什么。

如果是硬编码值,则只需编写:

std::cout << 24.00 << std::endl;

如果是整数变量,请编写以下内容:

std::cout << static_cast<double>(myIntegerVariable) << std::endl;

不要使用任何建议的方法,例如添加".00",因为如果您以后想更改精度,这会破坏您的代码。

重写完整性,请尝试以下

#include <iostream>
#include <iomanip>
int main()
{
int i = 24;
std::cout << std::fixed << std::setprecision(2) << double(i) << std::endl;
//    Output:  24.00
}