c#中最大值和最小值的重置

本文关键字:最小值 最大值 | 更新日期: 2023-09-27 18:10:50

我正在编写一个程序,该程序需要20个随机数,将它们分为4个部分,并计算每个部分的最小值和最大值。我遇到的问题是每次运行后将最小值和最大值重置为默认值。

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.IO;
 namespace 3
{
class Program
{
    static void Main(string[] args)
    {
        string ln;
        string line;
        int value = 0;
        int max = 0;
        int min = 100;
        using (TextReader tr = new StreamReader("values.txt"))
        {
            string currentLine = null;
            do
            {

                for (int i = 1; i < 6; i++)
                {
                    currentLine = tr.ReadLine();
                    if (currentLine == null)
                    {
                        break;
                    }
                    Console.WriteLine(currentLine);
                    value = int.Parse(currentLine);
                    if (value > max)
                   max=value;


                    if (i % 5 == 0)
                    {
                        Console.WriteLine("the Max is " + max);
                        Console.WriteLine("The Min is " + min);
                        Console.WriteLine("-----");
                    }


                }
            } while (currentLine != null);
            Console.ReadLine();
        }
    }
}
}

我的代码的错误是,我没有办法处理最大值,一旦最大值,或最小值,已经处理,无论是在文件的开头还是在中间。

c#中最大值和最小值的重置

您可以在"使用后"重置最大和最小值-在if块中,在打印后。使用赋值语句

举个简单的例子,8个数字分成2个部分。

对于数字9、2、5、4、7、1、2、8:

9、2、5、4在section 1中,7、1、2、8在section 2中。

在处理section 1时,得到max = 9和min = 2。您的代码正在做的是继续与第2节工作,而不将最大值和最小值重置为适当的值。你总是会得到9的最大值。

你应该做的是@David-B建议的;您应该重置最大值和最小值,就像您在开始时所做的那样。正确的位置是在您使用了最小值和最大值之后。