0

I want to find the largest number in an array then print them out, but I getting incorrect largest number output. Below is the output, as you can see the second and the third output for the largest number are incorrect.

enter image description here

Below is my code:

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

2 Answers 2

3

You never reset your max value, so it is still set as the max from the last calculation.

It will also fail when all values are below zero. You should initialise max to Integer.MIN_VALUE before each run.

Sign up to request clarification or add additional context in comments.

Comments

0

You are continuing to keep the max value from j Loop for the subsequent i loop.

Reset the value of Max to min value before the start of subsequent i loop. Also edit the initial declaration from sero to min value. Please refer below

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.