I have been tasked with writing a class with a non-empty array 'temperatures' which stores the temperatures of 365 days of a year.
My task is to write a method returning the day of the year with the lowest temperature. For example, if the array temperatures = {0,0,-10,-10,0,......,0}. The corresponding result should be 3, despite there being two equal values with the lowest temperature of the set, as the 3rd day (second index) was the first to have the lowest value.
I have correctly written out the code, however, I'm unsure as to why, in my second If statement, it returns only the day with the lowest value and not all the days with the lowest value.
Here's my code
public static int coldest(double[] temperatures) {
double minimum = temperatures[0];
for (double temp : temperatures) {
if (temp < minimum) {
minimum = temp;
}
}
for (int i = 0; i < temperatures.length; i++) {
if (Math.abs(minimum - temperatures[i]) < 0.000000001) {
return i + 1;
}
}
return -1;
}
For example, if I define double[] a = {-5,2,-5,2,-5,......2};, surely within the second For Loop, it will return 1,3,5,7... as all those days satisfy the If criteria, rather than just 1.
I apologise if I haven't written my question very clear, this is my first time asking here.
Thank you.
Aucun commentaire:
Enregistrer un commentaire