如何使用 for 循环找到最小值和最大值
how can I find the Min and Max with a for loop
你好,我的代码有问题我正在尝试使用 for 循环找到植物的最小高度和植物的最大高度,但我 运行 遇到了问题,我不能解决它(这在 C# BTW 中)
代码:
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);
将您的起始 min
和 max
调整为与初始输入相同。然后,在循环时,比较它们以查看值是大于还是小于当前的 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);
正如 Dmitry 所建议的,您甚至可以将 for
循环简化为将 return 中的 smaller/larger 数字简化为 min
/max
:
for (int i = 1; i <= 9; i++)
{
height = double.Parse(Console.ReadLine());
max = Math.Max(max, height);
min = Math.Min(min, height);
}
你好,我的代码有问题我正在尝试使用 for 循环找到植物的最小高度和植物的最大高度,但我 运行 遇到了问题,我不能解决它(这在 C# BTW 中) 代码:
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);
将您的起始 min
和 max
调整为与初始输入相同。然后,在循环时,比较它们以查看值是大于还是小于当前的 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);
正如 Dmitry 所建议的,您甚至可以将 for
循环简化为将 return 中的 smaller/larger 数字简化为 min
/max
:
for (int i = 1; i <= 9; i++)
{
height = double.Parse(Console.ReadLine());
max = Math.Max(max, height);
min = Math.Min(min, height);
}