从数组中查找最小值和最大值,最小值始终为0 [英] Find minimum and maximum number from array, minimum is always 0

查看:104
本文介绍了从数组中查找最小值和最大值,最小值始终为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();
    }
  }
}

但是最小值始终为0,为什么呢?

But minimum value is always 0, why is that?

推荐答案

您的问题是,您正在将 min max 初始化为 numbers [0] before 数字被填充,因此它们都被设置为零.对于 min (如果您的所有数字均为正)和 max (如果您的所有数字均为负)都是错误的.

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. This is wrong both for min (in case all your numbers are positive) and for max (in case all your numbers are negative).

如果您移动方块

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());
}

然后 min max 都将被初始化为第一个输入数字,这很好.实际上,您然后可以将 for 循环限制为仅检查后续数字:

then min and max will both be initialized to the first input number, which is fine. In fact you can then restrict your for loop to just check the subsequent numbers:

for (int i = 1; i < n; i++)
    ....

只需确保用户的 n 值大于零!

Just make sure the user's value of n is greater than zero!

这篇关于从数组中查找最小值和最大值,最小值始终为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆