x%2>0在java中是什么意思?

uhry853o  于 2021-07-08  发布在  Java
关注(0)|答案(4)|浏览(708)

我目前正在我的在线课程中学习java,我正在学习循环(特别是continue和break语句)。给我举的例子是:

int j = 0
while (true){
    System.out.println();
    j++;
    System.out.print(j);
    if (j%2 > 0) continue
    System.out.print(" is divisible by 2");
    if (j >= 10) break;
}

我不明白为什么是(j%2>0)而不是(j%2==0),因为如果“j”是5,而你做5%2呢。你得到的号码不是1吗?还是我遗漏了什么?有人能给我解释一下吗(对不起,我不是我的问题有点混乱。我以前从未使用过这个网站,而且我还很年轻)

vltsax25

vltsax251#

continue的意思是“转到循环的顶部,跳过循环的其余代码”,而不是“继续代码”。因此,由于5%2是1,并且1>0,因此将执行continue,直接转到循环的顶部并跳过正文的其余部分。
为什么他们用>0代替!=0? 没有任何技术上的原因,只是风格上的不同。我个人认为后者在我的脑海中更清晰。但两种方法都有效。

i86rm4rw

i86rm4rw2#

让我解释给你听。请参阅每行旁边的注解。

int j = 0          
while (true){
    System.out.println();
    j++;                   //increases the value of j on the next line by 1.
    System.out.print(j);   //prints 1, the first time because of above, 0 + 1.
    if (j%2 > 0) continue  //using modulus operator(%) we are doing 1 % 2, answer is 1
                           //since 1 % 2(if 1 is divisible by 2) > 0 we are 
                           //continue statement breaks the iteration in the 
                           //loop, so anything below this line won't be 
                           //executed.
    System.out.print(" is divisible by 2");//this line will only be executed
                                           //if j is divisible by 2. that is 
                                           //j is divisible by 2 (j%2 == 0)
    if (j >= 10) break;                    //when j is equal or greater than 
                                           //0 we are stopping the while loop.
}
bfrts1fy

bfrts1fy3#

x%2表示x除以2时的余数。所以如果x/2的余数大于0,就意味着x是奇数。当x%2==0时,则x为正数

l2osamch

l2osamch4#

int j = 0;
while (true){
    System.out.println();
    j++;
    System.out.print(j);
// in this case you won't print any message and you  
// are sure that the next number is even (j will be incremented by "continue;").
    if (j%2 > 0) continue; 
    System.out.print(" is divisible by 2");
    if (j >= 10) break;
}

相关问题