如何在C ++中固定数字长度 [英] How to fix a number length in C++

查看:102
本文介绍了如何在C ++中固定数字长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何固定浮点数,使其仅显示为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.

推荐答案

您知道在格式化字符串时会显示浮点数,例如:
You know when you format a string so that is displays a float, like so:
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.


请勿对货币值使用浮点数(或双精度数),因为它们可能会导致计算精度下降.您应该使用代表货币最小值(便士,美分等)的整数.
Don''t use floats (or doubles) for monetary values as they can lose precision in calculations. You should use integers representing the smallest value of the currency (pence, cents etc).


这篇关于如何在C ++中固定数字长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆