就1个 j 值在变化,看代码有解释,如下。 另外可以学一下调试,这种错误调试一下一目了然#include <stdio.h>
#include <math.h>
//输入 2 = 00000000 00000000 00000000 00000010
//输出 4294967294 = 11111111 11111111 11111111 11111110
int main(void){
int num_binary[32] = {0}, index;
unsigned int num, i, j = 32, a;
double count, total;
scanf("%u", &num);
while(num){
a = num % 2;
num_binary[j-1] = a;
num = num / 2;
j--;
}//此处j值已经改变并非32
for(i = 0;i < 32;i++){ //虽然此处用j不影响结果但是不符合逻辑
if(num_binary[i]==0){
num_binary[i] = 1;
}
else{
break;
}
}
j = 32;
for(index=0;index<31;index++){ //循环范围是0-31,j在变化
j--;
count = num_binary[index] * pow(2, j);
total += count;
}
printf("%u\n", (unsigned int)total);
return 0;
}
|