[英]Find minimum and maximum number from array, minimum is always 0
The program first asks the user for the number of elements to be stored in the array, then asks for the numbers.程序首先询问用户要存储在数组中的元素数量,然后询问数字。
This is my code这是我的代码
static void Main(string[] args)
{
Console.Write("How many numbers do you want to store in array: ");
int n = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[n];
int min = numbers[0];
int max = numbers[0];
for (int i = 0; i < n; i++)
{
Console.Write("Enter number {0}: ", i+1);
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < n; i++)
{
if (min > numbers[i]) min = numbers[i];
if (max < numbers[i]) max = numbers[i];
}
Console.WriteLine("The minimum is: {0}", min);
Console.WriteLine("The maximum is: {0}", max);
Console.ReadKey();
}
}
}
But minimum value is always 0, why is that?但最小值始终为 0,这是为什么呢?
Besides on your problem, you can use Enumerable.Min
and Enumerable.Max
methods like;除了您的问题,您还可以使用
Enumerable.Min
和Enumerable.Max
方法,例如;
int[] numbers = new int[]{1, 2, 3 ,4};
Console.WriteLine(numbers.Min()); //1
Console.WriteLine(numbers.Max()); //4
Don't forget to add System.Linq
namespace.不要忘记添加
System.Linq
命名空间。
Your issue is that you're initializing min
and max
to numbers[0]
before numbers is populated, so they're both getting set to zero.您的问题是在填充数字之前将
min
和max
初始化为numbers[0]
,因此它们都设置为零。 This is wrong both for min
(in case all your numbers are positive) and for max
(in case all your numbers are negative).这对于
min
(如果您的所有数字都是正数)和max
(如果您的所有数字都是负数)都是错误的。
If you move the block如果你移动方块
int min = numbers[0];
int max = numbers[0];
to after the block到后挡
for (int i = 0; i < n; i++)
{
Console.Write("Enter number {0}: ", i+1);
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
then min
and max
will both be initialized to the first input number, which is fine.然后
min
和max
都将被初始化为第一个输入数字,这很好。 In fact you can then restrict your for
loop to just check the subsequent numbers:实际上,您可以将
for
循环限制for
仅检查后续数字:
for (int i = 1; i < n; i++)
....
Just make sure the user's value of n
is greater than zero!只要确保用户的
n
值大于零即可!
You are initializing min
to 0.您正在将
min
初始化为 0。
Try following尝试以下
int min = Int32.MaxValue;
Also In case you are accepting negative values as input, you should initialize max to minimum integer value.此外,如果您接受负值作为输入,则应将 max 初始化为最小整数值。
int max = Int32.MinValue;
This code will help you in very simple way without adding any loops and conditions此代码将以非常简单的方式帮助您,而无需添加任何循环和条件
int[] arr={1,1,2,4,5,1,2,1};
Array.Sort(arr);
Console.WriteLine("Min no: "+arr[0]);
Console.WriteLine("Max no: "+arr[arr.Length-1]);
for (int i = 0; i < vector.GetLength(0); i++)
{
if (i == 0)
{
VectorMinMax[1]= vector[i];
VectorMinMax[0]= vector[i];
}
else {
if (VectorMinMax[1] > vector[i]) VectorMinMax[1] = vector[i];
if (VectorMinMax[0] < vector[i]) VectorMinMax[0] = vector[i];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.