如果我输入等于INTMax + 1的数字,计算机将不会返回-1 [英] Computer dosen't return -1 if I input a number equal to INTMax+1
问题描述
int类型是4字节长,我在Ubuntu下用C编写了一个小程序来打印我刚刚输入的数字.当我输入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.我修改了代码:
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是 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
调用后检查 errno
,您将看到它等于 ERANGE
(代码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)
这篇关于如果我输入等于INTMax + 1的数字,计算机将不会返回-1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!