%= 在 Java 中是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20085197/
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
What does %= mean in Java?
提问by Daniel
How does %= work in Java? I've been told that it can be used to reassign a value?
%= 在 Java 中如何工作?有人告诉我它可以用来重新分配一个值?
Grateful if anyone could teach! Thanks!
如果有人能教,不胜感激!谢谢!
minutes=0;
while(true){
minutes++;
minutes%=60;
}
采纳答案by pobrelkey
This is short for:
这是以下简称:
minutes = minutes % 60;
There are other, similar compound assignment operatorsfor all the binary operators in Java: +=
, -=
, *=
, ^=
, ||=
, etc.
还有其他类似的复合赋值运算符在Java中所有的二元运算符:+=
,-=
,*=
,^=
,||=
,等。
回答by nanofarad
+= is add to:
+= 添加到:
i+=2;
is i = i + 2;
是 i = i + 2;
%
is remainder: 126 % 10
is 6.
%
是余数:126 % 10
是 6。
Extending this logic, %=
is set to remainder:
扩展这个逻辑,%=
设置为余数:
minutes%=60;
sets minutes to minutes % 60
, which is the remainder when minutes
is divided by 60. This is to keep minutes from overflowing past 59.
将分钟设置为minutes % 60
,即minutes
除以 60的余数。这是为了防止分钟溢出超过 59。
回答by Elliott Frisch
It's a Modulo operationwhich is the same as taking the remainder from division. minutes%=60;
is the same as minutes = minutes % 60;
which is the same as minutes = minutes - (((int) (minutes/60)) * 60);
这是一个模运算,与从除法中取余数相同。minutes%=60;
是一样的minutes = minutes % 60;
是一样的minutes = minutes - (((int) (minutes/60)) * 60);