使用 for 循环查找奇数结果
Finding odd number results using the for loop
我在查找用户输入的奇怪结果时遇到了一些问题。我不确定如何编写 for 循环语句以仅获得奇数结果。当前的 for 循环语句固定为递增 2,但这仅在用户输入奇数以及 ex(0,5) 时才有效。抱歉,我真的没有多少 forloops 经验,我尝试嵌套 for 循环,但这只会让它更加混乱。这是我的 for 循环语句;
for(counter = num1; counter <= num2; counter+=2){ //this is my for loop statement
System.out.println(counter);//print out all of the odd values
}
}
如果用户输入的是偶数,在循环之前修正即可:
//if num1 is even, move it up to the next odd number
if (num1 % 2 == 0) {
num1++;
}
//print all of the odd values
for (int counter = num1; counter <= num2; counter+=2) {
System.out.println(counter);
}
作为已接受答案的替代:
//if num1 is even, move it up to the next odd number
num1 |= 1;
这可能并不重要,但我认为这样更整洁。
我在查找用户输入的奇怪结果时遇到了一些问题。我不确定如何编写 for 循环语句以仅获得奇数结果。当前的 for 循环语句固定为递增 2,但这仅在用户输入奇数以及 ex(0,5) 时才有效。抱歉,我真的没有多少 forloops 经验,我尝试嵌套 for 循环,但这只会让它更加混乱。这是我的 for 循环语句;
for(counter = num1; counter <= num2; counter+=2){ //this is my for loop statement
System.out.println(counter);//print out all of the odd values
}
}
如果用户输入的是偶数,在循环之前修正即可:
//if num1 is even, move it up to the next odd number
if (num1 % 2 == 0) {
num1++;
}
//print all of the odd values
for (int counter = num1; counter <= num2; counter+=2) {
System.out.println(counter);
}
作为已接受答案的替代:
//if num1 is even, move it up to the next odd number
num1 |= 1;
这可能并不重要,但我认为这样更整洁。