我的程序应该将十进制数转换为二进制数。 第一个for循环用于计算二进制数。 第二个循环将msb放入数组的第一个元素中。 这是一个练习,msb必须在第一个元素中。 我不明白错误在哪里,非常感谢帮助。
#include<stdio.h>
#include<stdlib.h>
int main(void){
int i;
int bits[16];
int bits_2[16];
int number;
int decimal;
int rest;
int msb;
int result=1;
printf( "Input number smaller than 65536: ");
scanf("%d", &decimal);
if(decimal >= 65536) {
printf( "\n\nincorrect input!");
return EXIT_FAILURE;
}
number=decimal;
for(i=0; result!=0; i++){
result = decimal / 2;
rest = result %2;
bits[i]=rest;
msb = i;
return msb;
}
printf("\n\n %d as binary number : ", number);
for(i=msb; bits[i]>=bits[0]; i--){
bits_2[msb-i] = bits[msb];
printf("%d", bits_2[msb-i]);
}
return 0;
}
答案 0 :(得分:1)
这是您的代码,其中包含一些更改以使其正常工作(您可以对其进行改进)
#include<stdio.h>
#include<stdlib.h>
int main(void){
int i;
int bits[16];
int bits_2[16];
int number;
int decimal;
int rest;
int msb;
int result=1;
printf( "Input number smaller than 65536: ");
scanf("%d", &decimal);
if(decimal >= 65536) {
printf( "\n\nincorrect input!");
return EXIT_FAILURE;
}
number=decimal;
for(i=0; result!=0; i++){
result = number / 2; //change this line
rest = number %2; // change this line
number=result; // add this line
bits[i]=rest;
msb = i;
// return msb; //delete this line
}
printf("\n\n %d as binary number : ", decimal); // change this line
for(i=msb; i+1; i--){ // change the condition
// bits_2[msb-i+1] = bits[msb]; // delete this line
printf("%d", bits[i]); // change this line
}
return 0;
}
答案 1 :(得分:1)
result = number = decimal;
for(bits[0]=msb=i=0; result != 0; i++){
bits[i] = result % 2;
result = result / 2;
msb = i;
}
printf("\n\n %d as binary number : ", number);
for(i=msb; i >= 0; i--){
bits_2[msb-i] = bits[i];
printf("%d", bits_2[msb-i]);
}
答案 2 :(得分:0)
我注意到你有很多无用的变量,所以这是你程序的 compact 版本:
#include <stdio.h>
#include <stdlib.h>
int main(void){
int i;
int bits[16];
unsigned int decimal;
int rest;
int result=1;
printf( "Input number smaller than 65536: ");
scanf("%d", &decimal);
if(decimal >= 65536) {
printf( "\n\nincorrect input!");
return EXIT_FAILURE;
}
else
printf("\n\n %d as binary number : ", decimal);
for(i=0; result!=0; i++){
result = decimal / 2;
rest = decimal %2;
decimal=result;
bits[i]=rest;
}
i--;
for(; i+1; i--){
printf("%d", bits[i]);
}
return 0;
}