gpt4 book ai didi

java - 在 Java 中使用模运算符

转载 作者:行者123 更新时间:2023-11-30 10:01:36 25 4
gpt4 key购买 nike

我想问一下如何使用模数运算,有人能告诉我如何使用 if 语句,为什么要使用 [== 0],但我们可以将模数计算的值分配给另一个变量。

为什么下面的代码有效?

     int number = 100;
if(number % 2 == 0)
{
sout(number);
}

为什么这个不使用 if 也能工作?

lastDigit = number % 10;

为什么下面的语句不起作用?

if(number % 2)
{
sout (number);
}

最佳答案

number % 2 是一个无法以任何方式计算为 boolean 值的表达式。

15.17.3. Remainder Operator %

The binary % operator is said to yield the remainder of its operands from an implied division; the left-hand operand is the dividend and the right-hand operand is the divisor.

https://docs.oracle.com/javase/specs/jls/se12/html/jls-15.html#jls-15.17.3

关于java - 在 Java 中使用模运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57350342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com