[英]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.