我正在尝试通过该程序将十进制转换为二进制,但是输出始终缺少最后一位。
例如,我将为 商 输入“ 123”,结果将是“ 111101”而不是“ 1111011”。我测试的每个输入都会发生这种情况。每个数字都在正确的位置,但最后一个数字丢失了。
任何帮助将不胜感激。
#include <stdio.h>
int main ()
{
int quotient = 123;
int i = 0;
int d1 = quotient % 2;
quotient = quotient / 2;
int c = 0;
int a = 0;
int number[32] = {};
while (quotient != 0)
{
i = i+1;
d1 = quotient % 2;
quotient = quotient / 2;
c++;
number[c]=d1;
}
for(a = 0; a < c; a = a + 1 )
{
printf("%d", number[c-a]);
}
return 0;
}
答案 0 :(得分:3)
问题是您在while
循环之前进行了一次划分:
int d1 = quotient % 2;
quotient = quotient / 2;
仅将其替换:
int d1 = 0;
事情应该会更好。
答案 1 :(得分:1)
您的代码中存在以下问题
应该在while循环中处理。
int d1 = quotient % 2;
quotient = quotient / 2;
您要在放入数组之前递增c
。
您的printf错误printf("%d", number[c-a]);
应该是printf("%d", number[c-a-1]);
您的完整代码
#include <stdio.h>
int main (){
int quotient = 15;
int i = 0;
int d1;
//quotient = quotient / 2;
int c = 0;
int a = 0;
int b = 0;
int number[32] = {};
while (quotient != 0){
d1 = quotient % 2;
quotient = quotient / 2;
number[c]=d1;
printf("%d\n", number[c]);
c++;
}
for(a = 0; a < c; a = a + 1 ){
printf("%d", number[c-a-1]);
}
return 0;
}