简体   繁体   English

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

[英]Improvement list the odd numbers code in C language

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");  }

I enter the input which '1' for 'low' variable while '10' for 'high' variable then it shows the result: "The odd numbers between 1 and 10 are 1 3 5 7 9. ".So, how can I improve or change my code by printing output:"The odd ..... 1,3,5,7,9."?我输入“1”代表“低”变量,而“10”代表“高”变量,然后它显示结果:“1 到 10 之间的奇数是 1 3 5 7 9。”那么,我怎么能通过打印输出改进或更改我的代码:“奇数..... 1,3,5,7,9。”?

To add commas添加逗号

 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);
   }
 }

could have been本来可以

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

. . Ie a single character, but I used %s just in case you want to add more padding即单个字符,但我使用 %s 以防万一您想添加更多填充

One nice thing about odd numbers is that you know exactly where they are.奇数的一个好处是您可以确切地知道它们在哪里。 Rather that iterating over all the values and checking if each is odd, just find the first odd value and increment by 2:而不是遍历所有值并检查每个值是否为奇数,只需找到第一个奇数并增加 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM