C从数字中提取数字

时间:2018-08-30 04:05:50

标签: c

我需要提取出奇数并给出输出,但是当我执行代码时,它给出了相反的想法。 例如1234 = 13,但是我的代码给了我31

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

    num /= 10;
}

4 个答案:

答案 0 :(得分:4)

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

digit = num % 10; 

您必须将其存储在数组中,并且在完成所有除法运算后仅打印它。

答案 1 :(得分:1)

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

#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

答案 2 :(得分:0)

很明显,它将输出31。

Coz,

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

num是1234

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

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

4将不会打印coz 4 % 2 != 0将返回false。

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

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

num是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循环迭代中继续执行此过程(称为debug),则会找到最终输出... 31。

答案 3 :(得分:0)

直接回答如下:

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

相关问题