如何查找0到9之间的所有其他奇数

时间:2014-11-14 04:31:29

标签: c

你好,我一直试图从0到9得到所有其他奇数,我几乎得到了它的工作,但由于某种原因它给了我3和7而不是3,7和9我去了关于如此解决它:

    int i = 0;
    int count = 1;
    for (; i < 10; i++)
    {
        if (i & 1)
        {
            count++;//add one if i is odd

            if (count & 1)//if count is odd then its the next odd
                printf("%d\n", i);//print i
        }

    }

1 个答案:

答案 0 :(得分:3)

这是一个更通用的解决方案,可以简化您的算法。

#include <stdio.h>

int main(void) {

    int max = 10;
    int first_odd = 3;
    int remainder = (first_odd % 4);
    for(int i = first_odd; i <= max; i++) {
        // every other odd is separated by 4, 
        // and will thus have the same remainder by 4
        if(i % 4 == remainder) {
            printf("%d\n", i); // prints 3, 7
        }
    }

    return 0;

}

或者,正如@keshlam所说,你可以硬编码:

#include <stdio.h>

int main(void) {
    int max = 10;
    int first_odd = 1; // or 3
    for(int i = first_odd; i <= max; i += 4) {
        printf("%d\n", i); // prints 1, 5, 9
    }
    return 0;
}