3

如果我输入的数字超过 5 位,则会显示错误的数字。例如:

Enter Integer: 123456
-7616 is EVEN.-7616 is ODD.

我的老师希望我们使用 Turbo C++,但它有时会在我运行程序后冻结,所以我使用了 OnlineGDB(https://www.onlinegdb.com)(语言:C(TurboC))。这是我的代码:

#include <stdio.h>
#include <conio.h>

int number;

int main()
{
    clrscr();
    
    printf("Enter Integer: ", number);
    scanf("%d", &number);
    
    if ((number%2)==0)
    {
        printf("%d is EVEN.", number);
    }
    
    printf("%d is ODD.", number);
    
    getch();
    return(0);
}
4

1 回答 1

1

它看起来像是int一个 16 位整数。123456 大于 16 位有符号整数限制(32767),因此scanf()不能将整数放入number. 相反,它会被截断。123456 以二进制表示为11110001001000000. 那是 17 位,但只有最后 16 位可以放入number. 最左边的位消失了,我们得到了1110001001000000,它是二进制补码形式的-7616(这是整数使用的形式)。

尝试使用更大的整数类型,例如long.

正如其他人在评论中建议的那样,您可能希望将printf()奇数放在else.

于 2021-11-15T08:27:34.240 回答