【问题标题】:C extracting odd digit from integerC从整数中提取奇数
【发布时间】:2019-02-04 22:18:36
【问题描述】:

我需要提取奇数并给出输出,但是当我执行代码时,它会以相反的顺序给我(例如,预期的输出是1234 = 13,但我的代码给了我31)。

int digit, num;
while (num > 0)
{
     digit = num % 10; 
    if(digit % 2 != 0)
    {
     printf("%d" , digit);
    }

    num /= 10;
}

【问题讨论】:

  • 当然。因为除法首先产生单位。您可以使用递归方法来反转打印
  • 在发布有关运行时问题时,就像这个问题一样,发布minimal reproducible example,以便我们可以重新创建问题,以便我们可以帮助您调试它

标签: c


【解决方案1】:

这是因为您首先在以下语句中打印除法运算的余数:

digit = num % 10; 

您必须将它存储在一个数组中,并且在所有分区完成后才打印它。

【讨论】:

    【解决方案2】:

    您首先打印单位。因此,您需要存储数据,或者使用递归方法,以便首先打印最后一个数字:

    #include <stdio.h>
    
    void podd(int num)
    {
       if (num > 0)
       {
          int digit = num % 10;
          if (digit % 2)
          {
            printf("%d" , digit);
          }
          podd(num / 10);
       }
    }
    
    
    int main() 
    {
      podd(1234);
      printf("\n");
      return 0;
    }
    

    (此处描述的经典 int 到字符串转换问题的变体:Convert integer to string without access to libraries

    【讨论】:

      【解决方案3】:

      显然,它会输出 31。

      因为,

      while 循环中的第一次迭代 =>

      数字是 1234

      digit = num % 10; 数字 = 1234 % 10(是 4)

      if(digit % 2 != 0)
          {
           printf("%d" , digit);
          }
      

      4 不会打印,因为 4 % 2 != 0 将返回 false。

      num /= 10; num = 1234 / 10 (num 现在是 123)

      while 循环中的第二次迭代 =>

      数字是 123

      digit = num % 10; 数字 = 123 % 10(是 3)

      if(digit % 2 != 0)
          {
           printf("%d" , digit);
          }
      

      将打印 3,因为 4 % 2 != 0 将返回 true。

      num /= 10; num = 123 / 10 (num 现在是 12)

      所以...我们得到了第一个数字 3。

      因此,如果您在下一次 while 循环迭代中继续此过程(称为调试),您将找到最终输出...即 31。

      【讨论】:

        【解决方案4】:

        直接回答如下:

        int num = 1234, digit = 0;
        do {
            digit = num % 10;           // Assigns the extracted digit to a variable named digit (ex: 4).
            if (digit % 2 != 0)         // Applies the formula to get the odd number.
                printf("%d\n", digit);  // Prints the odd number.
            num /= 10;                  // Extracts one digit each time (ex: 1234 / 10 = 123).
        } while (num > 0);              // Has reached the end of the number 'num'.
        

        结果:

        3
        1

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-10-18
          • 2023-03-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-27
          相关资源
          最近更新 更多