当您想每行打印一组数字时,模数如何工作

how does a modulus work when you want to print set of numbers per line

如果您想像下面给定的代码那样每行打印一组数字,有人可以向我解释模数是如何工作的吗?我只知道模数的作用就是给出一个数的余数而已。我想知道它经历的过程。

int []arrayLoterry= new int[50];
String output="";

   for(int i=0;i<arrayLoterry.length;i++){
      arrayLoterry[i]=(int) Math.floor(Math.random()*49)+i;
      output+=arrayLoterry[i]+" ";

      if(i%10==9){
         output+="\n";
      }
   }

System.out.println(output);

这条语句:

if(i%10==9){
    output+="\n";
}

表示:"If i divided by 10 leaves the remainder of 9, add "\n"(换行)到变量输出。

Moduli 只需将第一个数字除以第二个数字,然后给出余数。以下示例:

10%3 = 1  
20%2 = 0  
7%4 = 3

在您的情况下,这将在每 10 个数字后开始一个新的谎言。您可能会想,为什么不将该语句更改为 if(i%10 == 0) i%10 == 9 的原因是因为当循环第一次执行,i保存的是0的值,所以在遍历取模的时候,答案是0,在第一次执行循环后换行。

因为 Java 像我们计算 1、2、3 一样计算 0、1、2,所以我们必须在以 9 结尾的所有内容之后换行。因此,在第 9(第 10)之后开始新的一行对我们来说),第 19 个(对我们来说第 20 个),第 29 个(第 30 个),第 39 个(第 40 个)和第 49 个(第 50 个和最后一个)数字输出。

此图表显示了 Java 的计数方式与我们的计数方式。

Java | 0 1 2 3 4 5 6 7 8 9 
----------------------------
Us!! | 1 2 3 4 5 6 7 8 9 10

if 条件只是检查 i % 10 的余数是否为 9,然后在 if 块中执行任务。关于您的代码,基本上,在每个 10 数字附加到字符串 output 之后,一个换行符将附加到字符串 output 以分隔行。

示例:

when i == 9 // append newline
when i == 19 // append newline
when i == 29 // append newline
when i == 39 // append newline
when i == 49 // append newline

意味着最终结果将是一个 5 x 10 矩阵。

旁注 - 我不建议在循环中连接字符串,因为这是性能瓶颈,你最好使用 StringBuilder along with StringBuilder#append 方法。