有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:收藏。最大返回最大数字错误

给定一个循环,我想把最大的数字打印四次。有total_Atotal_Btotal_C并在这三个数字中找到最大的一个。但我在获得正确的最大值方面遇到了一些问题。数据训练1号和4号的输出正确,返回的数字最大,但2号和3号错误。以下是我的输出:

更新的输出

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) 个答案

  1. # 1 楼答案

    在整个循环中使用相同的集合,因此计算所有数据点的最大值。您犯了两个代码风格的错误,导致了此错误的发生:

    • 首先,你没有为你的变量选择合适的范围。因为它们是循环的本地对象,所以它们应该在循环内部声明,而不是在循环外部声明
    • 其次,构造一个集合来计算一个固定的、少量的数的最大值是过分的。只需使用Math.max(a, Math.max(b, c))

    更正后的代码是:

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