简体   繁体   English

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

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

It is easy to output a double value which is calculated to two decimal places. 输出一个双精度值很容易,它计算出两位小数。 And the code snippet is below: 代码片段如下:

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?

How to output an interger which is calculated to two decimal places? 如何输出一个整数到小数点后两位的整数? I want 24.00 as an output. 我想要24.00作为输出。

It depends on what your 24 is. 这取决于您的24岁。

If it is a hard-coded value, you can just write: 如果它是一个硬编码的值,则可以编写:

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

If it's an integer variable, write this: 如果它是整数变量,请编写以下代码:

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

Don't use any of the suggested approaches like adding ".00" as this will break your code if you want to change the precision later. 不要使用任何建议的方法,例如添加“ .00”,否则如果以后要更改精度会破坏代码。

A rewrite of completeness, please try with following 重写完整性,请尝试以下操作

#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