gpt4 book ai didi

java - 数组|使用数组除法查找重复整数?

转载 作者:行者123 更新时间:2023-12-01 07:00:43 25 4
gpt4 key购买 nike

如何让该方法显示重复的数字。这似乎是一个逻辑错误阻止了我,我不知道为什么代码没有执行它应该执行的操作。

  public static void findRepeating(int[] arr) { 
for (int i = 0; i< arr.length; i++) {
for(int d = 0; d<arr.length; d++) {
if(arr[i] / arr[d] == 1) {
System.out.println(arr[i] + " is repeating");
}
}
}
}


public static void main(String[] args) {

int[] myArray = {69, 7, 8, 9, 90, 666, 69, 420, 2};


findRepeating(myArray);

}

}

最佳答案

这里是对内部for循环中的逻辑和比较的更正

  public static void findRepeating(int[] arr) { 
for (int i = 0; i< arr.length; i++) {
for(int d = i+1; d<arr.length; d++) { //check with next element, as u will iterate over same element if iterating from start
if(arr[i] == arr[d]) { // checking for same number, as division can give 1 in multiple case for ex 11/7 is also 1
System.out.println(arr[i] + " is repeating");
}
}
}
}

关于java - 数组|使用数组除法查找重复整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55473736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com