例如,我得到三角形的面积为 6,我需要我的输出显示 006.000
我知道 SetPrecision 可以将小数位限制为三位,但我如何在解决方案前面放置零?
这就是我所拥有的
C边(3,4,5);
cout << std::fixed << std::setprecision(3);
cout << "nnttThe perimeter of this tringle is = " << Sides.Perimeter();
cout << "nnttThe area of the triangle is = " << Sides.Area();
cout << "nnttThe angle one is = " << Sides.Angleone();
cout << "nnttThe angle two is = " << Sides.Angletwo();
cout << "nnttThe angle three is = " << Sides.Anglethree();
cout << "nnttThe altitude one of the triangle = " << Sides.Altitudeone();
cout << "nnttThe altitude two of the triangle = " << Sides.Altitudetwo();
cout << "nnttThe altitude three of the triangle = " << Sides.Altitudethree();
输出为
The perimeter of this triangle is = 12.000
The area of the triangle is = 6.000
The angle one is = 90.000
The angle two is = 36.870
The angle three is = 53.130
The altitude one of the triangle = 2.400
The altitude two of the triangle = 6.667
The altitude three of the triangle = 3.750
但是我需要所有的答案都以这种形式出现,XXX.XXX 无论我的解决方案是什么。(因为值会改变)
任何帮助不胜感激,谢谢!
使用可以使用填充和填充机械手:
std::setfill('0'); // is persistent
//...
cout << std::setw(7) << value; // required for each output
使用来自 iomanip 和相关标头的 std::internal
、std::fixed
、std::setfill
、std::setw
和 std::setprecision
,您可以执行以下操作:
std::cout << std::fixed << std::setfill('0') << std::internal << std::setprecision(3);
std::cout << std::setw(7);
std::cout << 12.34f << "n";
并获得所需的输出。在科利鲁现场观看!
请参阅"格式":字符串和 I/O 格式(现代C++)
printf 函数可以做到这一点,请查看文档:http://www.cplusplus.com/reference/cstdio/printf/
您的案例有些独特,因为:(这些不是完整的代码片段,抱歉)
精度仅适用于浮点格式:
$ printf("%03.3fn", 6)
> 6.000
左填充仅适用于整数格式:
$ printf("%03.3dn", 6)
> 006
祝你好运,希望你能从这里拿走它