-1

hi I have problem in my code I'm trying to find the minimum height of a plant and the max height of the plant with a for loop but I'm running into a problem and I cant solve it (this in C# BTW) the code:

int i;
double height, min, max;
Console.WriteLine("Insert the height of plant");
height = double.Parse(Console.ReadLine());
min = 0;
max = 0;
for (i = 1; i <= 9; i++)
{
    height = double.Parse(Console.ReadLine());
    if(height >= max)
    {
        height = max;
    }
    if(height < max)
    {
        height = min;
    }
}
Console.WriteLine("Maximum hight = {0}", max);
Console.WriteLine("Minimum hight = {0}", min);
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
  • 5
    _" but I'm running into a problem "_ and the problem is? =) – Guru Stron Jan 12 '22 at 15:44
  • 2
    Also try to [debug](https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-debugger?view=vs-2022) your code - that will help you to find what is causing the issue. – Guru Stron Jan 12 '22 at 15:46
  • 3
    `min` and `max` are never changed because you have them reversed with `height`. `X = Y` assigns the value of `Y` to `X`. – Retired Ninja Jan 12 '22 at 15:48
  • 1
    In addition to the other troubles mentioned, I see you set min when testing max in one of the if's. – Bent Tranberg Jan 12 '22 at 15:51
  • 3
    `min = height;`, not `height = min;` – Dmitry Bychenko Jan 12 '22 at 15:53
  • welcome to StackOverflow. For the future please try and include into your question a much more precise problem description. You can always start with 1) Expected outcome: ... 2) Real outcome... – Mong Zhu Jan 12 '22 at 16:18

1 Answers1

1

Adjust your starting min and max to be the same as the initial input. Then, as you loop, compare those to see if the values are larger or smaller than the current min/max:

double height, min, max;
Console.WriteLine("Insert the height of plant");
height = double.Parse(Console.ReadLine());
min = height;
max = height;

for (int i = 1; i <= 9; i++)
{
    height = double.Parse(Console.ReadLine());

    if (height > max)
        max = height;
    if (height < min)
        min = height;
}
Console.WriteLine("Maximum hight = {0}", max);
Console.WriteLine("Minimum hight = {0}", min);

As suggested by Dmitry, you can even reduce your for loop to this to simply return the smaller/larger number into min/max:

for (int i = 1; i <= 9; i++)
{
    height = double.Parse(Console.ReadLine());

    max = Math.Max(max, height);
    min = Math.Min(min, height);
}
Austin
  • 2,203
  • 3
  • 12
  • 28