问题描述
如何固定浮点数,使其仅显示为3个数字?
例子
xx.x
13.4
即使浮点数是13.4355667.
How do you fix a float so that it only displays as 3 numbers?
example
xx.x
13.4
even when the float is 13.4355667.
推荐答案
char buff[32];
float number = 1.23456789f;
sprintf_s(buff, 32, "My Number: %f", number);
您可以通过使用%.2f
表示小数点后两位和%.8f
表示小数点后要打印的小数位数,以此类推.
我不确定是否有任何内置格式来限制有效数字的数量.因此,如果要3个有效数字,则1234567将变为123e4,而0.00015678将变为0.000157.但是您确实可以轻松控制小数位数.
如果您使用cout然后要限制小数位数,您需要执行以下操作:
You can specify the number of decimals to print after the point by using %.2f
for two decimal places and %.8f
for eight places and so on.
I''m not sure there''s any built in formatting to limit the number of significant digits though. So 1234567 would become 123e4 and 0.00015678 would become 0.000157 if you wanted 3 significant digits. But you do have some easy control over the number of decimal places.
If you''re using cout then to limit the number of decimal places you''d need to do this:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float num = 1.23456f;
cout << "My Number: " << setprecision(1) << num;
return 0;
}
输出将是"My Number: 1.2
"
传递给setprecision
的数字是您想要的小数位数.
Where the output would then be "My Number: 1.2
"
The number you pass to setprecision
is the number of decimal places you want.
这篇关于如何在C ++中固定数字长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!