【发布时间】:2023-03-19 02:43:01
【问题描述】:
我正在尝试通过这个程序将十进制转换为二进制,但输出总是缺少最后一位。
例如,我将为 商 输入“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;
}
【问题讨论】:
-
你在存储之前递增
c,所以第一个结果存储在number[1],而不是number[0] -
问题写得很好,谢谢。有所有需要回答的问题,但不要太多。
-
@SanderDeDycker 我已经编辑了问题...等待接受
-
@YesThatIsMyName:还有一个……
-
我能理解的唯一变量是`商`。我向你保证,在 6 个月后你也会如此。养成编写可维护代码的习惯,这意味着至少有意义的变量名,必要时使用 cmets。
标签: c arrays missing-data