简体   繁体   English

printf浮点变量和常量之间有什么区别?

[英]what's the difference between printf a floating-point variable and constant?

Here's my code: 这是我的代码:

float x = 21.195;
printf("%.2f\n", x);
printf("%.2f\n", 21.195);

I would expect both print statements to have identical output, but instead, the first prints 21.19 , and the second prints 21.20 . 我希望两个打印语句具有相同的输出,但相反,第一个打印21.19 ,第二个打印21.20

Could someone explain why the output is different? 有人能解释为什么输出不同吗?

The values are different. 价值观不同。 The first is a float , which is typically 4 bytes. 第一个是float ,通常是4个字节。 The second is a double , which is typically 8 bytes. 第二个是double ,通常是8个字节。

The rules for rounding are based on the third digit after the decimal place. 舍入规则基于小数位后的第三位数。 So, in one case, the value is something like 21.19499997 and the other 21.1950000000001, or something like that. 因此,在一种情况下,值类似于21.19499997,而另一个21.1950000000001,或类似的东西。 (These are made up to illustrate the issue with rounding and imprecise numeric formats.) (这些用于说明舍入和不精确的数字格式的问题。)

By default 21.195 is a double. 默认情况下,21.195是双倍的。

If you want a float, write : 如果你想要一个浮点数,写:

21.195F

or 要么

(float)21.195

Regards 问候

When a floating point variable is defined in C, by default it is set to double . 当在C中定义浮点变量时, 默认情况下它设置为double So x is set to float because you mentioned it explicitly , else 21.195 is considered to be double. 所以x 设置为float,因为你明确提到它,否则21.195被认为是double。

Now, as mentioned above, float is usually about 4 bytes and double is about 8 bytes . 现在,如上所述, float通常约为4个字节double约为8个字节 So a float value has 24 significant bits with 7 digits of precision and double has 53 significant bits with 15 to 16 digits of precision . 因此浮点值有24位有效位,7位精度 53位有效位,精度为15到16位

A roundoff function %.2f works to round off the number correct to 2 decimal places and checks the third digit after the decimal point for rounding off. 舍入函数%.2f用于将正确的数字四舍五入到小数点后两位,并检查小数点后的第三个数字以进行四舍五入。 So 21.195 in float expands to 21.19499998 and is then reduced to 21.19 after %.2f an 21.195 in double expands to 21.1950000000000001 and hence reduces to 21.20. 所以21.195在浮动中扩大到21.19499998然后在%。2之后减少到21.19,双重扩大到21.1950000000000001,因此减少到21.20。

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM