gpt4 book ai didi

c - 输出不会在某个值之后出现

转载 作者:行者123 更新时间:2023-11-30 19:01:50 25 4
gpt4 key购买 nike

下面编写的代码将十进制转换为二进制。该代码在 1009 之前给出正确的输出。之后,它给出错误的输出。为什么这样?int 保证至少能够存储 -32767 到 32767 范围内的值。

 #include<stdio.h>

int main() {
int remainder, n = 0;
long binary = 0;
int i = 1;
scanf("%d",&n);
while (n != 0)
{
remainder = n % 2;

binary = binary + remainder * i;
i = i * 10;

n = n / 2;
}

printf("%ld", binary); // Be sure to use "%ld" with `long`.
return 0;
}

示例运行:

INPUT:  1100
OUTPUT: 1411066508

最佳答案

After that onwards it gives wrong output. Why so?

以下 2 个中的任何一个溢出。值远超过 32767。

binary=binary+remainder*i;
i=i*10;

尝试使用此代码进行演示。

printf("before: binary %ld, remainder %d, i  %d\n", binary, remainder, i);
binary=binary+remainder*i;
i=i*10;
printf("after: binary %ld, remainder %d, i %d\n", binary, remainder, i);

请注意,一旦发生有符号整数溢出,那就是未定义的行为并且任何事情都可能发生。

<小时/>
#include<stdio.h>

int main() {
int remainder, n = 0;
long int binary = 0;
int i = 1;
n = 1010;
while (n != 0) {
remainder = n % 2;
printf("before: binary %10ld, remainder %d, i %10d\n", binary, remainder, i);
binary = binary + remainder * i;
i = i * 10;
printf("after: binary %10ld, remainder %d, i %10d\n", binary, remainder, i);
n = n / 2;
}
printf("%ld", binary); // Be sure to use "%ld" with `long`.
return 0;
}

输出

before: binary          0, remainder 0, i           1
after: binary 0, remainder 0, i 10
before: binary 0, remainder 1, i 10
after: binary 10, remainder 1, i 100
before: binary 10, remainder 0, i 100
after: binary 10, remainder 0, i 1000
before: binary 10, remainder 0, i 1000
after: binary 10, remainder 0, i 10000
before: binary 10, remainder 1, i 10000
after: binary 10010, remainder 1, i 100000
before: binary 10010, remainder 1, i 100000
after: binary 110010, remainder 1, i 1000000
before: binary 110010, remainder 1, i 1000000
after: binary 1110010, remainder 1, i 10000000
before: binary 1110010, remainder 1, i 10000000
after: binary 11110010, remainder 1, i 100000000
before: binary 11110010, remainder 1, i 100000000
after: binary 111110010, remainder 1, i 1000000000
before: binary 111110010, remainder 1, i 1000000000
after: binary 1111110010, remainder 1, i 1410065408
1111110010

i 变为 10,000,000,000 时,其值将超过 INT_MAX

关于c - 输出不会在某个值之后出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57136081/

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