c# - 从数组中查找最小和最大数,最小值始终为 0

标签 c#

程序首先询问用户要存储在数组中的元素数量,然后询问数字。

这是我的代码

    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,这是为什么?

最佳答案

除了您的问题,您还可以使用 Enumerable.MinEnumerable.Max方法如;

int[] numbers = new int[]{1, 2, 3 ,4};
Console.WriteLine(numbers.Min()); //1
Console.WriteLine(numbers.Max()); //4

不要忘记添加 System.Linq命名空间。

关于c# - 从数组中查找最小和最大数,最小值始终为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20019990/

相关文章:

c# - Linq-to-SQL:组合(或运算)多个 "Contains"过滤器?

c# - 如何公开 C# "using"别名以避免 "inconsistent accessibility"错误?

c# - EF 和 IHostedService 的多个实例

javascript - 信号器向连接的客户端发送评论,但在特定帖子内

c# - 为什么我上传到 Azure 的图像包含无法显示的错误?

c# - 使用C#.Net连接到hadoop集群

c# - 使用 Caliburn.Micro.Contrib 通用对话框

c# - 使用 RavenDB 实现存储库和服务模式

c# - 请求在 WCF IIS 服务器中堆积

c# - 可能是 Visual Studio 2015 中的 C# 编译器错误