Java if 语句中的奇数或偶数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26315283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:12:52  来源:igfitidea点击:

Odd or even number in if statement

javaif-statement

提问by Eoin Ronayne

I'm using robot world for an assignment. we have to get to robot to go north 8 places then east 6 places. when we get to the point the robot has a choice to make. if there is an even number of beepers in that see the robot should face north and move one cell. if there is an odd number of beepers then it should face south and move one. I don't know what command to give the robot in the source code. my program runs when i just have

我正在使用机器人世界进行作业。我们必须让机器人去北 8 个地方然后东 6 个地方。当我们到达点时,机器人可以做出选择。如果其中有偶数个蜂鸣器,则机器人应朝北并移动一个单元格。如果有奇数个蜂鸣器,那么它应该朝南并移动一个。不知道源码里给机器人什么命令。我的程序在我刚运行时运行

if(beeperPresent)) {
    turnLeft();
    move();
} else {
    turnRight();
    move();
}

回答by Gordonium

Eoin, an effective way of calculating odd or even numbers is to use the modulo operator. It's very simple.

Eoin,计算奇数或偶数的有效方法是使用模运算符。这很简单。

if (number % 2 == 0) numberIsEven
if (number % 2 != 0) numberIsOdd

You could use this logic in your code to calculate if there are an even or odd number of beepers.

您可以在代码中使用此逻辑来计算是否有偶数或奇数的蜂鸣器。

回答by Henri Lapierre

Example:

例子:

int number1 = 1;
int number2 = 2;

if (number1 % 2 == 0) {
    // You won't get here
}

if (number2 % 2 == 0) {
   // You will get here
}

The "%" is called modulo, and it returns the remaining of the division.

“%”称为模数,它返回除法的剩余部分。

  • 3 % 2, the remaining of 3/2 is 1, so you know it's odd
  • 4 % 2, the remaining of 4/2 is 0, so you know it's even
  • 3 % 2,3/2 的余数是 1,所以你知道它是奇数
  • 4 % 2,4/2 的剩余部分是 0,所以你知道它是偶数

回答by Henri Lapierre

I think you are doing programming methodology course of Stanford university and having your assignment on Karel. Nice to see this. Coming back to your problem, for this case, you can use a counter to check how many beepers are present (initially set to Zero, just increment the counter if you pick a beeper). Pick beepers until all are picked up. Then, finally check if the counter is divisible by 2 or not to check its even or odd.

我认为您正在上斯坦福大学的编程方法课程并在 Karel 上完成您的作业。很高兴看到这个。回到您的问题,在这种情况下,您可以使用计数器来检查存在多少蜂鸣器(最初设置为零,如果您选择蜂鸣器,只需增加计数器)。选择蜂鸣器,直到全部被拾起。然后,最后检查计数器是否可被 2 整除以检查其偶数或奇数。