我正在尝试用 C 编写十进制到二进制转换器的代码。我必须使用 unsigned long long int 因为我必须能够计算的最大数字是 18,446,744,073,709,551,615。在我的教授让我们使用的Linux服务器上,它说存在分段错误,并且在CLion调试器上它说“Exception = EXC_BAD_ACCESS(code = 2,address = 0x7ff7bc694ff8)”并声称i = {unsigned long long} 18446744073708503289,其中不对。无论 userInput 的数量是多少,它都会执行此操作。
我目前拥有的:
#include <stdio.h>
int main(void)
{
unsigned long long int userInput;
unsigned long long int i;
unsigned long long int binary[] = {};
printf("Enter a number from 0 to 18,446,744,073,709,551,615: ");
scanf("%lld", &userInput);
printf("\nThe binary value of %lld is: ", userInput);
if (userInput == 0)
{
printf("0");
}
else
{
for (i = 0; userInput > 0; i++)
{
binary[i] = userInput%2;
userInput = userInput/2;
}
for (i -= 1; i >= 0; i--)
{
printf("%lld", binary[i]);
}
}
printf("\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
由于binary没有给出明确的大小并且给出了空的初始值设定项列表,因此该数组的大小为 0。任何使用此类数组的尝试都将触发未定义的行为,在这种特殊情况下会导致崩溃。
您最多需要存储 64 个二进制数字,因此请确保数组的大小。
unsigned long long int binary[64];
Run Code Online (Sandbox Code Playgroud)
另一个问题是在这个条件中:
for (i -= 1; i >= 0; i--)
Run Code Online (Sandbox Code Playgroud)
因为i有unsigned类型,所以条件i >= 0永远为真。因此将 的类型更改i为int.
int i;
Run Code Online (Sandbox Code Playgroud)