c - 改进列出C语言中的奇数代码

void main() {
int low, high, odds = 0;
do {
    printf("Please enter a number:");
    rewind(stdin);
    scanf("%d", &low);
} while (low <= 0);
do {
    printf("Please enter the second number:");
    rewind(stdin);
    scanf("%d", &high);
} while (high < 2 * low);
printf("The odd numbers between %d and %d are: ", low, high);
for (odds = low;odds <= high;odds++) {
    if (odds % 2 != 0)
    {
        printf(" %d", odds);
    }
}
printf(".\n");
system("pause");  }

我输入“1”代表“低”变量,而“10”代表“高”变量,然后它显示结果:“1 到 10 之间的奇数是 1 3 5 7 9。”那么,我怎么能通过打印输出改进或更改我的代码:“奇数..... 1,3,5,7,9。”?

回答1

添加逗号

int first = 1;
 for (odds = low;odds <= high;odds++) {
   if (odds % 2 != 0)
   {
     if(first){ // to prevent comma before first number
        first = 0;
     }  else {
         printf("%s",",");
     }
     printf(" %d", odds);
   }
 }

本来可以

printf("%c", ',');

.即单个字符,但我使用 %s 以防万一您想添加更多填充

回答2

奇数的一个好处是您可以确切地知道它们在哪里。而不是遍历所有 values 并检查每个是否为奇数,只需找到第一个奇数 value 并增加 2:

#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char **argv)
{
    int low = argc > 1 ? strtol(argv[1], NULL, 10) : 1;
    int high = argc > 2 ? strtol(argv[2], NULL, 10) : 10;
    printf("The odd numbers between %d and %d are: ", low, high);
    if( low % 2 == 0 ){
        low += 1;
    }
    for( int odd = low; odd <= high; odd += 2 ){
        printf("%s%d", odd == low ? "" : ", ", odd);
    }
    putchar('.');
    putchar('\n');
    return 0;
}