为什么使用 %3.3f 打印值为 2.5367 的浮点数输出 2.537 而不是 2.536?
Why does printing a float having value 2.5367 using `%3.3f` output 2.537 instead of 2.536?
#include<stdio.h>
void main()
{
float f = 2.5367;
printf("%3.3f",f);
}
输出为:2.537
但是怎么办?
我认为输出应该是 2.536
但输出是 2.537
。
The precision value specifies the number of digits after the decimal point. If a decimal point appears, at least one digit appears before it. The value is rounded to the appropriate number of digits.
也就是说,请使用其他书籍或资源进行学习,谁教你可以使用 void main()
是完全错误的,不应该教 C.
因为2.5367更接近2.537。 2.536 的增量为 0.007,而 2.537 的增量仅为 0.003。
你想做的只是删除其字符串表示的最后一个字符,这在数学上是错误的。
除了现有的答案外,请注意许多 C 编译器都试图遵循 IEEE 754 来处理浮点问题。 IEEE 754 建议根据当前舍入模式进行舍入,以便从二进制浮点数转换为十进制。默认的舍入模式是“四舍五入到最接近的,并连到偶数”。部分编译平台不考虑四舍五入方式,浮点数转十进制时始终按照默认的最近偶数方式进行四舍五入。
由于float f = 2.5367需要四舍五入,小数点后有3位,所以值为2.***,即2.537。
#include<stdio.h>
void main()
{
float f = 2.5367;
printf("%3.3f",f);
}
输出为:2.537
但是怎么办?
我认为输出应该是 2.536
但输出是 2.537
。
The precision value specifies the number of digits after the decimal point. If a decimal point appears, at least one digit appears before it. The value is rounded to the appropriate number of digits.
也就是说,请使用其他书籍或资源进行学习,谁教你可以使用 void main()
是完全错误的,不应该教 C.
因为2.5367更接近2.537。 2.536 的增量为 0.007,而 2.537 的增量仅为 0.003。
你想做的只是删除其字符串表示的最后一个字符,这在数学上是错误的。
除了现有的答案外,请注意许多 C 编译器都试图遵循 IEEE 754 来处理浮点问题。 IEEE 754 建议根据当前舍入模式进行舍入,以便从二进制浮点数转换为十进制。默认的舍入模式是“四舍五入到最接近的,并连到偶数”。部分编译平台不考虑四舍五入方式,浮点数转十进制时始终按照默认的最近偶数方式进行四舍五入。
由于float f = 2.5367需要四舍五入,小数点后有3位,所以值为2.***,即2.537。