java java中的%运算符是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43975824/
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-11-03 07:51:20  来源:igfitidea点击:

What is the % operator in java?

java

提问by LipstickQueen

public static int sumDigits (int n) {
  if(n < 10)
    return n;
  else
    return n%10 + sumDigits (n/10);
}

This method is used to calculate the sum of the digits in a number recursively, but I do not understand it? What is the purpose of n%10???

这个方法是用来递归计算一个数的各位数之和的,但是我不明白?n%10 的目的是什么???

回答by Eran

n%10gives you the least significant digit of nby calculating the remainder of dividing the number by 10.

n%10n通过计算将数字除以 10 的余数,为您提供 的最低有效位。

Hence, the method returns the sum of the least significant digit and the sum of digits of n/10(which is the number that contains all the digits of nexcept of the least significant digit).

因此,该方法返回最低有效数字的总和和 的数字总和n/10(即包含n除最低有效数字之外的所有数字的数字)。

回答by Raman Sahasi

n%10means modulus of 10. This is used to get last digit.

n%10表示 的模数10。这用于获取最后一位数字。

Let's say your number is 12345

假设你的号码是 12345

12345 % 10means remainder when 12345is divided by 10, which gives you 5.

12345 % 10表示12345除以时的余数10,得到5

Thereafter when you perform (n/10)you get 1234(all the numbers except the least significant digit that you got in previous step).

此后,当您执行时,您(n/10)将获得1234(除上一步中获得的最低有效数字之外的所有数字)。

回答by SPlatten

% is modulus, so n mod 10, it returns the remainder after n / 10.

% 是模数,所以 n mod 10,它返回 n / 10 之后的余数。

if n is 1 to 10, then it will return 1 to 9 and 0 when n is 10.

如果 n 是 1 到 10,那么当 n 是 10 时,它将返回 1 到 9 和 0。

回答by Stuti Rastogi

n%10means the modulus of 10, that is the remainder you get when you divide with 10. Here it is used to get each digit.

n%10表示10的模数,也就是你除以10得到的余数。这里用来得到每个数字。

Example:

例子:

Say your number is n = 752.

假设您的数字是 n = 752。

n%10 = 2, n/10 = 75

n%10 = 2, n/10 = 75

So you add 2 to the sumDigits(75)

所以你把 2 添加到 sumDigits(75)

Now, n%10 = 75%10 = 5. This is the digit to be added and so on, till your n >= 10. When it is < 10, you have a single digit that you just need to return as it is, as that is only the sum of digits in that single-digit number n.

现在,n%10 = 75%10 = 5。这是要添加的数字,依此类推,直到您的n >= 10. 当它是 时< 10,您只需要按原样返回一位数字,因为这只是该一位数字 n 中的数字之和。