计算机这么想的返回-1,如果我输入一个数目等于INTMax +1 [英] Computer dosen't return -1 if I input a number equal to INTMax+1
问题描述
int类型为4个字节长,我在C写在Ubuntu下一个小步骤打印我有只输入数字。当我输入2147483648,即2 ^ 31,它打印2147483647,而不是-1。同样的事情发生时,我比投入较大2147483647任意数量为什么没有溢出-1作为我学习形式的书,但似乎截断INT_MAX,并在位水平发生了什么?
The type int is 4-byte long and I wrote a little procedure in C under Ubuntu to print the number I've just input. When I input 2147483648, i.e. 2^31, it prints 2147483647 rather than -1. The same thing happens when I input any number larger than 2147483647. Why doesn't it overflow to -1 as I learnt form book but seems like truncated to INT_Max and what happened in the bits level?
#include <stdio.h>
int main(){
int x;
scanf("%d",&x);
printf("%d\n",x);
}
我犯了一个错误。 INT_MAX + 1应该等于INT_MIN。我修改了code:
I made a mistake. INT_Max+1 should equal to INT_Min. I modified the code:
#include <stdio.h>
int main(){
int x=2147483647;
int y=x+1;
printf("%d",y);
}
和输出 -2147483648
现在,我只是想知道发生了什么事,当我调用该函数scanf函数?我想这一切截断比2147483647较大输入的号码为2147483647。
and the output is -2147483648
Now I'm just wondering what happened when I call the function scanf? I think it truncated all the input number larger than 2147483647 to 2147483647.
推荐答案
2147483647即INT_MAX的重新presentation是为0x7FFFFFFF
。结果
如果你加1,你会得到一个未定义行为。结果
这就是说,在实践中,如果添加1,您将获得为0x80000000
即-2147483648。结果
我不知道为什么你期望-1作为二进制编码为 0xFFFFFFFF的
。
The representation of 2147483647 ie INT_MAX is 0x7FFFFFFF
.
If you add 1, you'll get an undefined behaviour.
This said, in practice, if you add 1, you'll get 0x80000000
ie -2147483648.
I don't know why you expect -1 as its binary encoding is 0xFFFFFFFF
.
#include <stdio.h>
#include <errno.h>
int main(){
int val1 = 2147483647;
int val2 = val1+1;
int x;
printf("errno before : %d\n",errno);
scanf("%d",&x); //enter 2147483648 or a larger value
printf("errno after : %d\n\n",errno);
printf("val1 = %d (0x%X)\n", val1, val1);
printf("val2 = %d (0x%X)\n", val2, val2);
printf("x = %d (0x%X)\n", x, x);
return 0;
}
输出:
errno before : 0
errno after : 34 //0 if the entered value is in the range of 4-bytes integer
val1 = 2147483647 (0x7FFFFFFF)
val2 = -2147483648 (0x80000000)
x = 2147483647 (0x7FFFFFFF)
为什么你的原因 X = 2147483647
是 scanf函数
钳制值的可能范围。
如果检查错误号
在 scanf函数
电话,你会看到,它等于 ERANGE
(code 34)
The reason why you get x=2147483647
is that scanf
clamps the value to the possible range.
If you check errno
after scanf
call, you will see that it is equal to ERANGE
(code 34)
这篇关于计算机这么想的返回-1,如果我输入一个数目等于INTMax +1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!