2017-03-05 5 views
-2

ループを考えると、最大の数字を4回印刷したいと思う。 total_A,total_B,total_Cがあり、これら3つの中で最大の番号を見つけます。しかし、私は正しい最大数を取得するいくつかの問題に直面している。最大の数値を返すデータトレーニングno.1とno.4の出力は正しいですが、no.2とno.3は間違っています。以下は私の出力です:Java:Collections.maxは最大の数値エラーを返す

更新出力以下

enter image description here

私のコードです:

public class Multiclass2 { 
    public static void main(String args []){ 
     double x [][] = {{3.24,-0.96}, 
        {-1.56,-0.61}, 
        {-1.1,2.5}, 
        {1.36,-4.8}; 

    double [] wA = {0,1.94,3.82}; 
    double [] wB = {0,-4.9,-4.03}; 
    double [] wC = {0,4.48,3.25}; 

    double threshold = 1; 
    int n = x.length; 
    double total_A = 0; 
    double total_B = 0; 
    double total_C = 0; 
    List<Double> li = new ArrayList<Double>(); 
    double max = 0; 



    for(int i=0;i<n;i++){ 

     System.out.println("For training data point no." + (i+1)); 

      total_A = (threshold * wA[0]) + (x[i][0] * wA[1]) + (x[i][1] * wA[2]); 

      total_B = (threshold * wB[0]) + (x[i][0] * wB[1]) + (x[i][1] * wB[2]); 

      total_C = (threshold * wC[0]) + (x[i][0] * wC[1]) + (x[i][1] * wC[2]); 


      li.add(total_A); 
      li.add(total_B); 
      li.add(total_C); 
      max = Collections.max(li); 

      System.out.println(total_A+", "+total_B+", "+total_C); 
      System.out.println("MAx is "+max); 


    } 



} 
} 
+1

? – Jeremy

+2

コードはコンパイルされず、コンパイルされても表示された出力は生成されません...実際の回答を得るための実際のコードが必要です – Dici

+3

MCVEを入力してください。つまり、自分自身でコンパイルして実行できるコード、サンプル入力、およびサンプル入力の**予想される**出力です。 –

答えて

2

あなたは、ループ全体accross同じコレクションを使用しているので、あなたがしていますALLデータ点の最大値を計算する。あなたは、このバグを起こす2つのコードスタイルミスをしました。

  • まず、変数に適切なスコープを選択しませんでした。それらはループのローカルなので、ループ内で宣言してください。
  • 第2に、固定された少数の数値の最大値を計算するためのコレクションを作成することは過度です。ただ、Math.max(a, Math.max(b, c))

を使用する修正されたコードは次のようになります。 `から来number`ん

public static void main(String args[]) { 
    double x[][] = { 
     { 3.24, -0.96 }, 
     { -1.56, -0.61 }, 
     { -1.1, 2.5 }, 
     { 1.36, -4.8 } 
    }; 

    double[] wA = { 0, 1.94, 3.82 }; 
    double[] wB = { 0, -4.9, -4.03 }; 
    double[] wC = { 0, 4.48, 3.25 }; 

    double threshold = 1; 

    int n = x.length; 
    for (int i = 0; i < n; i++) { 
     System.out.println("For training data point no." + (i + 1)); 

     double total_A = (threshold * wA[0]) + (x[i][0] * wA[1]) + (x[i][1] * wA[2]); 
     double total_B = (threshold * wB[0]) + (x[i][0] * wB[1]) + (x[i][1] * wB[2]); 
     double total_C = (threshold * wC[0]) + (x[i][0] * wC[1]) + (x[i][1] * wC[2]); 

     double max = Math.max(total_A, Math.max(total_B, total_C)); 

     System.out.println(total_A + ", " + total_B + ", " + total_C); 
     System.out.println("Max is " + max); 
    } 
} 
+1

申し訳ありません、ありがとうございます。 –

関連する問題