簡體   English   中英

無法在數組中獲得兩個相等數字的兩個位置

[英]Cannot get the two places of 2 equal numbers in an array

我正在嘗試編寫一個程序來確定最大的數字是多少,同時我制作了一個包含 20 個變量的數組。 我正在嘗試檢查我是否有 2 個相同且最大的數字。 如果它們相同,那么我想顯示兩個數字。 由於某種原因,它總是寫最大的數字,但它總是顯示有 2 個 arrays 最大的數字與最大的數字相同,但數組中的兩個數字之一是錯誤的。 你能幫我改正嗎? 謝謝!

        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);
            
        }

你的問題是兩個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也顯示結果,我更正了您的最后一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM