如何在c#中为任意数量的数字编写平均方程

时间:2017-11-13 21:05:32

标签: c# average

我的目标是生成一个人在框中输入的数字的平均值(我已经设置了)。等式需要在f.Close()之后;并且数据类型需要浮动。

public partial class frmMain : Form
{
    public frmMain()
    {
        InitializeComponent();   
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
        int total = 0, count = 0;
        DialogResult result;
        result = ofd.ShowDialog();
        if (result == System.Windows.Forms.DialogResult.OK)
        {
            string fileName = ofd.FileName;
            StreamReader f = new StreamReader(fileName);

            while (!f.EndOfStream)
            {
                string textScore = f.ReadLine();
                firstScores.Items.Add(textScore);
                int score = int.Parse(textScore);
                total = total + score;
                count = count + 1;
            }

            f.Close();

            //This is what I have currently
            float sum, length, average;
            string textLine;

            sum = float.Parse(textLine);
            length = float.Parse(textLine);
            average = sum / length;

我认为这可能有用,但是它声明sum = float.Parse中的textLine是未分配的。

2 个答案:

答案 0 :(得分:3)

  

在sum = float.Parse中的textLine是未分配的。

你将这两条线放在一起:

string textLine;
sum = float.Parse(textLine);

您刚刚宣布textLine,但尚未存储任何内容。

您真正想要做的是使用您已从文件中读取的数据。当您阅读该文件时,您将该数据放入firstScores.Items集合中,并且您已经计算了totalcount。您只需要使用这些相同的值,并确保强制 Parse())将它们转移到float以避免integer division ,这将截断小数部分(链接是为老式C编写的,但内容对于C#也是如此)。

顺便说一下,你还在学习,教授可能会为你完成使用StreamReader等过程的具体目标。但我认为同样值得向你展示我&# 39; d在真实的工作计划中这样做:

//First, separate out the this code into a function that accepts a file name and returns the values via the IEnumerable interface, rather than an array or list
IEnumerable<int> ReadScores(string filename)
{ 
    //Use the `System.IO.File` class to make reading simpler
    // and use the linq functions to get this down to a single line of code:
    return File.ReadLines(filename).Select(l => int.Parse(l));
}

private void btnOpen_Click(object sender, EventArgs e)
{
    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        //ToList() is optional, but it will force the data into memory, so we only need to go disk once
        var data = ReadScores(ofd.FileName).ToList();

        int total = data.Sum();
        int count = data.Count;
        float average = (float)total / (float)count;
    }
}

答案 1 :(得分:1)

平均值是总数除以计数。你已经获得了总数和数量。

你已经有了一个提示 - 它们需要是浮点数,而不是整数,所以像这样抛出它们:

float floatTotal = (float)total;
float floatCount = (float)count;

然后做你的数学运算:

float average = floatTotal / floatCount;

您还需要检查您是否正在除以零(即:该计数> 0)。如果您没有阅读任何分数,这将使您的程序崩溃。