JFX*_*erd 0 c++ cout decimal-point
我正在开发一个需要通过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;
Run Code Online (Sandbox Code Playgroud)
这是输出:
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
有人可以告诉我为什么这种变化是精确发生的,我可以做些什么来解决它?
谢谢
小智 5
您需要使用"固定"模式.在默认浮点模式下,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;
}
Run Code Online (Sandbox Code Playgroud)
给出输出:
3.1
3.14
Run Code Online (Sandbox Code Playgroud)
HTH.
| 归档时间: |
|
| 查看次数: |
163 次 |
| 最近记录: |