[英]C++ - Why is my cout code displaying decimals inconsistently?
我正在開發一個需要通過cout在一行上打印一個數組並顯示2個小數位的應用程序。 目前,我的代碼以2個小數打印前兩個項目,然后切換到1。
這是代碼:
cout << " Inches ";
cout << showpoint << setprecision(2) << right;
for (int i = 0; i < 12; i++)
{
cout << setw(5) << precipitation[i];
}
cout << endl;
這是輸出:
Inches 0.72 0.89 2.0 3.0 4.8 4.2 2.8 3.8 2.7 2.1 1.6 1.0
有人可以告訴我為什么這種變化是精確的嗎,我該怎么做才能解決?
謝謝
您需要使用“固定”模式。 在默認浮點模式下,precision()設置要顯示的有效數字的數量。 在“固定”模式下,它設置小數點后的位數。 例子:
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
float pi = 3.14;
cout.precision(2);
cout << pi << endl;
cout << fixed << pi << endl;
}
給出輸出:
3.1
3.14
HTH。
如果只在輸出語句前添加showout和setprecision固定的cout <<固定,您將獲得所有輸出的一致格式。
見下文:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double precipitation[12] = { .72, .89, 2, 3, 4.8, 4.2, 2.8, 3.8, 2.7, 2.1, 1.6, 1 };
cout << " Inches ";
cout << showpoint << fixed << setprecision(2) << right;
for (int i = 0; i < 12; i++)
{
cout << setw(5) << precipitation[i];
}
cout << endl;
return 0;
}
現在,輸出將如下所示:
Inches 0.72 0.89 2.00 3.00 4.80 4.20 2.80 3.80 2.70 2.10 1.60 1.00
我也為這個問題感到困擾。 您需要使用“固定”來執行此操作。
請參閱此鏈接: C ++ setprecision(2)打印一個小數?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.