c - 如何找出0到9之间每隔一个奇数

标签 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
        }

    }

最佳答案

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

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

关于c - 如何找出0到9之间每隔一个奇数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26922916/

相关文章:

c - 如何在C中的while循环中存储数组索引的值

c - 从 c 中的 .in 文件读取

c - 错误 C2143 : syntax error : missing ';' before 'type'

用于绘制 DFA、NFA 的 C 库

创建 4D 查找表

无法理解这段代码的作用

c - 如何找到领先的数字

c - 使用 C 中的 rand 函数用字母表填充数组

c++ - 使用 scanf 和 printf 会使程序无限循环,但通过替换 cin 和 cout 可以正常工作

c - arm_cft_sR_q31_len4096 未声明