c#读取文本文件找到最小最大平均值

时间:2016-04-14 07:56:08

标签: c#

我在TAFE学习,但是班级和我自己都没有得到讲师的帮助。

我需要从txt文件中读取并从中找到最小值和平均值并将其打印到控制台。

上一个练习是从数组中获得最大平均值,我已经写了这个并且它工作正常。我正在使用VS2012。

我已经编写了代码来读取文本文件并将其打印到控制台 - 但我找不到最大最大值和平均值。我得到“对象引用未设置为对象的实例”。当我运行程序时。

请注意,我使用相同的代码来查找数组的最大平均值...我觉得这可能是问题,但我无法解决它!

这是我的数组代码......

a = [1:2,2:3]

class A {
    def m() {
        println a
    }

}


new A().m()

如上所述这很好用。现在我的问题...... 我编写了代码来显示文本文件中的数据,如下所示,我的评论......

        static void Main(string[] args)
        {
            int[] hoursArray = { 1, 24, 9, 7, 6, 12, 10, 11, 23, 8, 2, 9, 8, 8, 9, 7, 9, 15, 6, 1, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8 };
            for (int i = 0; i < hoursArray.Length; i++)
            {
                Console.WriteLine(hoursArray[i].ToString());
            }

            {

                {
                    int low = hoursArray[0];
                    for (int index = 1; index > hoursArray.Length; index++)
                    {
                        if (hoursArray[index] < low)
                        {
                            low = hoursArray[index];
                        }
                    }

                    Console.WriteLine("Lowest Hours Parked = " + low);

                int high = hoursArray[0];
                for (int index = 1; index < hoursArray.Length; index++)
                {
                    if (hoursArray[index] > high)
                    {
                        high = hoursArray[index];
                    }
                }

                Console.WriteLine("Highest Hours Parked = " + high);

                    int total = 0;
                    double average = 0;
                    for (int index = 0; index < hoursArray.Length; index++)
                    {
                        total = total + hoursArray[index];
                    }

                    average = (double)total / hoursArray.Length;
                    Console.WriteLine("Average Hours Parked =" + average.ToString("N"));

                    Console.ReadLine();
                }
            }
        }
    }
}

3 个答案:

答案 0 :(得分:4)

我建议使用 Linq

// First of all define the source - it can be an array, file - whatever:
// var source = hoursArray; // e.g. source for the array
var source = File
  .ReadLines(@"C:\MyFile.txt")         //TODO: put actual file here
  .SelectMany(line => line.Split(',')) //TODO: put actual separator here
  .Select(item => int.Parse(item));

// having got source (IEnumerable<int>) let's compute min, max, average

int max = 0;
int min = 0;
double sum = 0.0; // to prevent integer division: 7/2 = 3 when 7.0 / 2 = 3.5
int count = 0;
boolean firstItem = true;

foreach (item in source) {
  sum += item; 
  count += 1;

  if (firstItem) {
    firstItem = false;
    max = item;
    min = item;
  } 
  else if (item > max)
    max = item;
  else if (item < min)
    min = item;
}

// Finally, formatted output
Console.Write("Min = {0}; Max = {1}; Average = {2}", min, max, sum / count);

答案 1 :(得分:0)

使用File.ReadLines读取文件内容,然后使用简单的int语句将其转换为Linq数组。

int[] hoursArray = File
  .ReadLines("filepath")  // Read all lines,
  .SelectMany(s => s.Split(",").Select(int.Parse)) // Split by ',' and convert them to int.
  .ToArray(); 

执行此操作后,其余代码应按原样运行。

还有一个建议,数组上有预定义的方法/函数来获取AverageMinMax

你可以这样做。

var avg = hoursArray.Average();
var min = hoursArray.Min();
var max = hoursArray.Max();

答案 2 :(得分:0)

string text = System.IO.File.ReadAllText("filePath");
        int[] hoursArray = (text.Split(' ').ToArray()).Select(x => Convert.ToInt32(x)).ToArray();
        int max = hoursArray.Max();
        int min = hoursArray.Min();
        double avg = hoursArray.Average();