gpt4 book ai didi

如果我输入一个等于 INT_Max+1 的数字,计算机不会返回 -1

转载 作者:太空宇宙 更新时间:2023-11-04 06:32:05 24 4
gpt4 key购买 nike

int 类型是 4 个字节长,我在 Ubuntu 下用 C 写了一个小程序来打印我刚刚输入的数字。当我输入 2147483648,即 2^31,它打印 2147483647 而不是 -1。当我输入大于 2147483647 的任何数字时,也会发生同样的事情。为什么它不会溢出到 -1,就像我从表格书上学到的那样,但似乎被截断为 INT_Max 以及位级别发生了什么?

#include <stdio.h>
int main(){
int x;
scanf("%d",&x);
printf("%d\n",x);
}

我错了。 INT_Max+1 应等于 INT_Min。我修改了代码:

#include <stdio.h>
int main(){
int x=2147483647;
int y=x+1;
printf("%d",y);
}

输出为-2147483648现在我只是想知道当我调用函数 scanf 时发生了什么?我认为它将所有大于 2147483647 的输入数字截断为 2147483647。

最佳答案

通过 C99 标准 6.5 表达式:

If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.

看这里:

int i = 2147483648;
printf("%d",i);

http://ideone.com/07THjV

void main()

顺便说一句,main 返回 int

关于如果我输入一个等于 INT_Max+1 的数字,计算机不会返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19491933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com