Java:数组返回最大数字错误

时间:2017-03-04 11:09:38

标签: java arrays

我想找到一个数组中最大的数字,然后将它们打印出来,但是我得到了不正确的最大数字输出。下面是输出,您可以看到最大数字的第二个和第三个输出不正确。

enter image description here

以下是我的代码:

double x [][] = {{3.24,-0.96},
                 {-1.56,-0.61},
                 {-1.1,2.5},
                 {1.36,-4.8}};
String y [] = {"B","C","A","C"};
double w[][] = {{0,1.94,3.82},{0,-4.9,-4.03},{0,4.48,3.25}};
double threshold = 1;
int n = x.length;
int m = w.length;
double total [] = new double[3];
double max = 0;
double input = 0;

for(int i=0;i<n;i++){
     for(int j=0;j<m;j++){
          total[j] = (threshold * w[j][0]) + (x[i][0] * w[j][1]) + (x[i][1] * w[j][2]);
          System.out.print(total[j] +", ");
          input = total[j];
          max = Math.max(input,max);
     }

     System.out.println();
     System.out.println("Maximum is "+ max);
}

2 个答案:

答案 0 :(得分:3)

您永远不会重置max值,因此它仍设置为上次计算的最大值。

当所有值都低于零时,它也会失败。您应该在每次运行之前将max初始化为Integer.MIN_VALUE

答案 1 :(得分:0)

您将继续保持j loop的最大值,以用于后续的i循环。

在后续i循环开始之前将Max的值重置为最小值。同时编辑从sero到min值的初始声明。 请参考下面的

double x [][] = {{3.24,-0.96},
                 {-1.56,-0.61},
                 {-1.1,2.5},
                 {1.36,-4.8}};
String y [] = {"B","C","A","C"};
double w[][] = {{0,1.94,3.82},{0,-4.9,-4.03},{0,4.48,3.25}};
double threshold = 1;
int n = x.length;
int m = w.length;
double total [] = new double[3];
double max = Integer.MIN_VALUE;
double input = 0;

for(int i=0;i<n;i++){
     for(int j=0;j<m;j++){
     total[j] = (threshold * w[j][0]) + (x[i][0] * w[j][1]) + (x[i][1] * w[j][2]);
      System.out.print(total[j] +", ");

input = total[j];
max = Math.max(input,max);
}

System.out.println();
System.out.println("Maximum is "+ max);
 max = Integer.MIN_VALUE;
}