繁体   English   中英

如何输出一个整数到小数点后两位的整数?

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

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

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM