首页 > 解决方案 > 无法在数组中获得两个相等数字的两个位置

问题描述

我正在尝试编写一个程序来确定最大的数字是多少,同时我制作了一个包含 20 个变量的数组。我正在尝试检查我是否有 2 个相同且最大的数字。如果它们相同,那么我想显示两个数字。出于某种原因,它总是写入最大的数字,但它总是显示有 2 个数组,其中最大的数字与最大的数字相同,但数组中的两个数字之一是错误的。你能帮我改正吗?谢谢!

        int b,c=Integer.MIN_VALUE,d = 0,r = 0;
        boolean s= false;
        int[] a = new int[20];
        for(b = 0 ; b < a.length ; b++) {
            a[b] = (int) (Math.random()*899+100);
            System.out.print(a[b] + "     ");
            if(a[b]==c) {
                r = b;
                s = true;
            }
                
            if(a[b]>= c) {
                c = a[b];
                d = b;
            }


        }
        if (s = true) {
            System.out.println("the biggest number was " + c + " and it was placed in the array at " + d + " as well as at " + r + " place" );
            
            
        }
        else {
            System.out.println("the biggest number was " + c + " and it was placed in the array at " + d);
            
        }

标签: java

解决方案


你的问题是if里面的两个for

如果你有a[b] == c,那么这两个都if将被读取。所以,这是有效的:

int b,c=Integer.MIN_VALUE,d = 0,r = 0;
boolean s= false;
int[] a = new int[20];
for(b = 0 ; b < a.length ; b++) {
     a[b] = (int) (Math.random()*899+100);
     System.out.print(a[b] + "     ");

     if(a[b] > c) {
          s = false ;
          c = a[b];
          d = b;
      } else if(a[b] == c) {
          s = true;
          r = b;
      }
}

if (s) {
     System.out.println("the biggest number was " + c + " and it was placed in the array at " + d + " as well as at " + r + " place" );
} else {
     System.out.println("the biggest number was " + c + " and it was placed in the array at " + d);
}

我更正了你的最后一个if以显示结果。


推荐阅读