【问题标题】:My array printf loop is missing one digit at the end我的数组 printf 循环最后缺少一位数字
【发布时间】: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


【解决方案1】:

问题是您在 while 循环之前进行了一次除法:

int d1 = quotient % 2;
quotient = quotient / 2;

将其替换为:

int d1 = 0;

事情应该会更好。

【讨论】:

    【解决方案2】:

    您的代码存在以下问题

    1. 应该在while循环中处理。

      int d1 = quotient % 2; quotient = quotient / 2;

    2. 在放入数组之前,您正在递增 c

    3. 你的 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-11
      • 2019-08-31
      • 2019-11-06
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 2017-06-16
      相关资源
      最近更新 更多