为什么scanf为大浮点数输入错误? [英] Why is scanf taking the wrong input for large float numbers?
问题描述
#include< stdio.h>
int main(){
float k;
scanf(%f,& k);
printf(%f,k);
$ b在这个简单的程序中,当我输入一个最多包含8个数字的数字时,显示正确。
但是,如果我超过了8位,即输入 123456789
,输出是 123456792
。
为什么会这样呢?那么有趣的是,如果我在 123456789
和 123456796
之间输入任何数字,那么它总是显示 123456792
。
是否与浮点数的8位精度有关?
解决方案浮点类型的精度有限。对于你的机器上的一个 float
,看起来是32位的,它有24位的精度(23位被显式存储,1位被隐含)。这意味着整数大于〜16000000,这需要超过24位来存储,不能用这个数据类型准确表示。
例如,您使用的值123456789有一个二进制表示:
111 0101 1011 1100 1101 0001 0101
这个值占用了27比特,比可用的多。所以它被四舍五入为可以用23位存储的最接近的值,即123456792.在二进制中:
111 0101 1011 1100 1101 0001 1000
对于这个值,值3的低3位没有显式存储。 / p>
#include <stdio.h>
int main() {
float k;
scanf("%f", &k);
printf("%f", k);
}
In this simple program when I enter a number containing at most 8 digits then it is displayed correctly.
But if I exceed 8 digits i.e. for the input 123456789
the output is 123456792
.
Why this is happening? Well the fun fact is that if I enter any number between 123456789
and 123456796
then it always shows 123456792
.
Is it something related to the 8 decimal precision of floating numbers?
解决方案 Floating point types have a limited precision. For a float
on your machine, which appears to be 32 bit, it has 24 bits of precision (23 explictly stored, 1 implied). That means integers greater than ~16000000, which require more than 24 bits to store, can't be represented exactly with this datatype.
For example, the value 123456789 you used has a binary representation of:
111 0101 1011 1100 1101 0001 0101
This value takes up 27 bits which is more than is available. So it is rounded to the closest value that can be stored with 23 bits, which is 123456792. In binary:
111 0101 1011 1100 1101 0001 1000
For this value, the lower 3 bits with value 0 are not explicitly stored.
这篇关于为什么scanf为大浮点数输入错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!