1

例如,我得到一个三角形的面积为 6,我需要我的输出显示 006.000

我知道 setprecision 可以将小数位限制为三位,但我如何在我的解决方案前面放置零?

这就是我所拥有的

CTriangle Sides(3,4,5);

cout << std::fixed << std::setprecision(3);

cout << "\n\n\t\tThe perimeter of this tringle is   = " << Sides.Perimeter();

cout << "\n\n\t\tThe area of the triangle is        = " << Sides.Area();

cout << "\n\n\t\tThe angle one is                   = " << Sides.Angleone();

cout << "\n\n\t\tThe angle two is                   = " << Sides.Angletwo();

cout << "\n\n\t\tThe angle three is                 = " << Sides.Anglethree();

cout << "\n\n\t\tThe altitude one of the triangle   = " << Sides.Altitudeone();

cout << "\n\n\t\tThe altitude two of the triangle   = " << Sides.Altitudetwo();

cout << "\n\n\t\tThe 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 提供所有答案。(因为值会改变)

任何帮助表示赞赏,谢谢!

4

4 回答 4

3

使用可以使用填充填充操纵器:

std::setfill('0');             // is persistent
//...

cout << std::setw(7) << value; // required for each output
于 2014-02-24T00:41:06.223 回答
2

使用std::internal, std::fixed, std::setfill, std::setwand std::setprecisionfrom iomanip和相关的头文件,你可以:

std::cout << std::fixed << std::setfill('0') << std::internal << std::setprecision(3);

std::cout << std::setw(7);
std::cout << 12.34f << "\n";

并获得所需的输出。在 Coliru 现场观看!

于 2014-02-24T00:53:55.183 回答
1

请参阅“格式”:字符串和 I/O 格式化(现代 C++)

于 2014-02-24T00:37:40.747 回答
1

printf 函数可以为您执行此操作,请查看文档: http ://www.cplusplus.com/reference/cstdio/printf/

您的案例有些独特,因为:(这些不是完整的代码片段,抱歉)

精度仅适用于浮点格式:

$ printf("%03.3f\n", 6)
> 6.000

左填充仅适用于整数格式:

$ printf("%03.3d\n", 6)
> 006

祝你好运,希望你能从这里拿走它

于 2014-02-24T00:37:49.113 回答