簡體   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