gpt4 book ai didi

c - 整数范围和溢出

转载 作者:行者123 更新时间:2023-12-03 07:40:24 26 4
gpt4 key购买 nike

这是一个将正十进制数转换为二进制数的简单程序。我必须报告并停止转换那些可能导致溢出或错误结果的数字。我发现整数的大小为4字节,但它只能正确转换到1023。
我混淆数字“1023”来自哪里?有什么方法可以计算,以便我可以预测正确的范围,如果说,我正在另一个系统上编程。

#include<stdio.h>
int main(void)
{
int decimal,binary=0,y,m=1;
scanf("%d",&decimal);
if(decimal<=1023)
{
while(decimal>0)
{
y=decimal%2;
binary=binary+(m*y);
m=m*10;
decimal=decimal/2;
}
printf("\nBinary Equivalent is: %d",binary);
}
else
{printf("Sorry, The Number You've entered exceeds the maximum allowable range for conversion");}
getch();
return 0;

}

最佳答案

1023等于1024-1(2 ^ 10 -1),因此小于或等于1023的数字的底数为2。由于您使用int来获取结果,因此它最多可存储2 ^ 31,因为该数字等于10。 -1 = 2147483647(31,因为32位之一用于表示符号(+或-))。当您使用1024或更高的数字时,它使用10位数以上-因此,它大于2147483647。

希望能有所帮助。

关于c - 整数范围和溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26019089/

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