大家好,我一直在尝试获取 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/