[英]Need my output to be in this form XXX.XXX c++
例如我得到一個三角形的面積為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格式。(因為值會改變)
任何幫助表示贊賞,謝謝!
使用iomanip和相關標頭中的std::internal
, std::fixed
, std::setfill
, std::setw
和std::setprecision
std::setfill
,您可以執行以下操作:
std::cout << std::fixed << std::setfill('0') << std::internal << std::setprecision(3);
std::cout << std::setw(7);
std::cout << 12.34f << "\n";
並獲得所需的輸出。 在Coliru上現場觀看!
請參見“格式”: 字符串和I / O格式(現代C ++)
printf函數可以幫助您查看文檔: http : //www.cplusplus.com/reference/cstdio/printf/
您的案例有些獨特,因為:(這些不是完整的代碼段,歉意)
精度僅適用於浮點格式:
$ printf("%03.3f\n", 6)
> 6.000
左填充僅適用於整數格式:
$ printf("%03.3d\n", 6)
> 006
祝你好運,你可以從這里拿走
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.