My task is: Data on the height of N students in a class are entered in turn. Determine the average, minimum and maximum height of students in the group.
I wrote such a solution, but the program incorrectly outputs the maximum and minimum values.
Console.Write("Number of students in the group = ");
int n = Convert.ToInt32(Console.ReadLine());
double result = 0;
double min = 0;
double max = 0;
for (double i = 0.0; i < n; i++)
{
Console.Write("The height of {0} student (in cm): ", i + 1);
double h = Convert.ToDouble(Console.ReadLine());
result += h;
if (max > h) max = h;
if (h < max) min = h;
}
double average = 0;
average = result / n;
Console.WriteLine("Average value = " + average);
Console.WriteLine("Maximum value = " + max);
Console.WriteLine("Minimun value = " + min);
Output:
What can I do to fix this?
if (h < max) min = h; is a bug, since at the start all values =0, and since height will never be less then 0, and will never be true and min will stay 0 forever.
if (max > h) max = h; does not make much sense too for the same reason. Max is 0 at the start, so it will never be true and max will be 0 forever.
Try this
static void Main()
{
Console.Write("Number of students in the group = ");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(n.ToString());
double result = 0;
double min = 0;
double max = 0;
for (var i = 0; i < n; i++)
{
Console.Write("The height of {0} student (in cm): ", i + 1);
double h = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(h.ToString());
result += h;
if (h > max) max = h;
if ( min==0 || h < min) min = h;
}
double average = result / n;
Console.WriteLine("Average height = " + average);
Console.WriteLine("Maximum height = " + max);
Console.WriteLine("Minimun heignt = " + min);
}
output
Number of students in the group = 5
The height of 1 student (in cm): 140
The height of 2 student (in cm): 150
The height of 3 student (in cm): 130
The height of 4 student (in cm): 170
The height of 5 student (in cm): 165
Average heignt = 151
Maximum heignt = 170
Minimun heignt = 130
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.