Java 百分比符号 (%) 是什么意思?

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

What does the percentage symbol (%) mean?

java

提问by Mohamed Moamen

I ran into some code containing the %symbol inside the array argument.

我遇到了一些包含%数组参数中的符号的代码。

What does it mean and how does it work?

它是什么意思以及它是如何工作的?

Example:

例子:

String[] name = { "a", "b", "c", "d" };

System.out.println(name[4 % name.length]);
System.out.println(name[7 % name.length]);
System.out.println(name[50 % name.length]);

Output:

输出:

a
d
c

采纳答案by T.J. Crowder

That's the remainder operator, it gives the remainder of integer division. For instance, 3 % 2is 1because the remainder of 3 / 2is 1.

那是余数运算符,它给出整数除法的余数。例如,3 % 21因为其余3 / 21

It's being used there to keep a value in range: If name.lengthis less than 4, 7, or 50, the result of % name.lengthon those values is a value that's in the range 0to name.length - 1.

它被用于在那里保持的值在范围:如果name.length小于4,7,或50,结果% name.length这些值是一个值,该值的范围为0name.length - 1

So that code picks entries from the array reliably, even when the numbers (4, 7, or 50) are out of range. 4 % 4is 0, 7 % 4is 3, 50 % 4is 2. All of those are valid array indexes for name.

因此,即使数字(4、7 或 50)超出范围,该代码也能可靠地从数组中选取条目。4 % 407 % 4350 % 42。所有这些都是name.

Complete example (live copy):

完整示例(实时复制):

class Example
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String[] name = { "a" , "b" , "c" , "d"};
        int n;
        n = 4 % name.length;
        System.out.println(" 4 % 4 is " + n + ": " + name[n]);
        n = 7 % name.length;
        System.out.println(" 7 % 4 is " + n + ": " + name[n]);
        n = 50 % name.length;
        System.out.println("50 % 4 is " + n + ": " + name[n]);
    }
}

Output:

输出:

 4 % 4 is 0: a
 7 % 4 is 3: d
50 % 4 is 2: c

回答by GhostCat

Simple: this is the modulo, or to be precise the remainderoperator.

简单:这是modulo,或者准确地说是余数运算符。

This has nothing to do with arrays per se. It is just a numerical computation on the value that gets used to compute the array index.

这与数组本身无关。它只是对用于计算数组索引的值进行数值计算。