Home > Back-end >  Why is my program for calculating an average getting a NaN error?
Why is my program for calculating an average getting a NaN error?

Time:11-22

    import java.util.*;
import java.io.*;
public class Experiment {
public static void main(String args[]){
   double temps[] = {27.5,34.4};
   int k = 0;
   double total = 0;
   double avgTemp;
   while(temps.length < k)
   {
       k  ;
      total  = temps[0];
      System.out.println("Temp: "   temps[0]);
      temps[0] = temps[0   1];
    }
       avgTemp = total / k;
      System.out.println("Average: "   avgTemp);
   }// end file
  }// end class

This code is everything, so if I'm missing something please let me know. I tried putting the 1 on the outside of the temps[] array inside the while loop, and I tried to establish the variables in the while loop as well, which didn't help the NaN problem.

CodePudding user response:

because of this condition while(temps.length < k) while loop will never execute as temps.length will always greater than k i.e 0.

At the end it will divide

avgTemp = total / k;

avgTemp = 0/0;
  • Related