我的数组 printf 循环在末尾缺少一位数字
My array printf loop is missing one digit at the end
我正在尝试通过此程序将十进制转换为二进制,但输出总是缺少最后一位数字。
例如,我将为 quotient 输入“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;
}
问题是您在 while
循环之前除法一次:
int d1 = quotient % 2;
quotient = quotient / 2;
将其替换为:
int d1 = 0;
事情应该会更好。
您的代码存在以下问题
应该在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;
}
我正在尝试通过此程序将十进制转换为二进制,但输出总是缺少最后一位数字。
例如,我将为 quotient 输入“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;
}
问题是您在 while
循环之前除法一次:
int d1 = quotient % 2;
quotient = quotient / 2;
将其替换为:
int d1 = 0;
事情应该会更好。
您的代码存在以下问题
应该在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;
}