繁体   English   中英

如何让程序检查数组 arr 的每个元素是否是同一数组的其他元素的倍数?

[英]How to make the program check if each element of the array arr is a multiple of each other element of the same array?

所以我需要程序来检查数组中的每个元素是否是同一个数组中其他元素的倍数。 根据用户输入,如果是 6 个整数,您将被要求输入 6 个整数。 假设您输入 100、25、20、40、5。结果应该是:100 是 25 的倍数,100 是 20 的倍数,等等。

public static void main(String[] args) {
    Scanner kbd = new Scanner(System.in);
    int sum = 0;
    int n;
    do {
        System.out.print("Enter an integer n greater than 1: ");
        n = kbd.nextInt();
    } while (n < 2);
    System.out.println();

    int[] arr = new int[n];
    System.out.print("Enter " + n + " integers : ");
    for (int i = 0; i < arr.length; i++) {
        arr[i] = kbd.nextInt();
    }
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] % arr[i] == 0) {
            System.out.println(arr[i] + " is a multiple of " + arr[i]);
        }
    }
}

您应该在阵列上运行两次以检查 2 个不同的索引。 尝试用它切换最后一个 for 循环:

for(int i = 0; i < arr.length; i++){
    for(int j = 0; j < arr.length; j++){
       if(i!=j && arr[i]%arr[j]==0){
           System.out.println(arr[i] + " is a multiple of " + arr[j]);
       }
     }
  }

在数组上使用 2 循环并检查索引 i 和索引 j 处的元素

        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length && i != j; j++) {
                if (arr[i] % arr[j] == 0) {
                    System.out.println(arr[i] + " is a multiple of " + arr[j]);
                }
            }
        }

, output

100 is a multiple of 25
100 is a multiple of 20
100 is a multiple of 5
25 is a multiple of 5
20 is a multiple of 5
40 is a multiple of 20
40 is a multiple of 5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM