如何从C中的scanf输入整数开始打印递减的奇数?

Gen*_*Gen 2 c while-loop

如果输入偶数,则只打印奇数,直到它达到 0。(不打印 0)。例如,如果您输入 10,则输出将为 9、7、5、3、1。

这就是我想出的。我想知道我应该如何减少 x 以获得所需的输出。

int x;
scanf("%d", &x);
while (x >= 0) {
  printf("%d", x);
  x = x - 2;
}
Run Code Online (Sandbox Code Playgroud)

Bob*_*b__ 5

我想知道我应该如何减少 x 以获得所需的输出。

减去 2 没问题,只要你总是从一个奇数开始。所以你可以把循环改成这样:

for ( int i = x % 2 ? x : x - 1; // Is x odd? good. 
                                 // Otherwise, start from the previous one.
      i > 0;
      i -= 2 ) {
    printf("%d\n", i);
}
Run Code Online (Sandbox Code Playgroud)