从文本文件C#计算平均值

时间:2015-08-23 11:36:26

标签: c# average

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        var WriteToFile = new System.IO.StreamWriter("student.txt"); //create textfile in default directory
        WriteToFile.Write(txtStudNum.Text + ", " + txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
        WriteToFile.Close();
        this.Close(); 
    }

    catch (System.IO.DirectoryNotFoundException ex)
    {
        //add error message
    }
}

private void button3_Click(object sender, EventArgs e)
{
    File.AppendAllText("student.txt", "\r\n" + txtStudNum.Text + ", " +  
    txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
}

private void button4_Click(object sender, EventArgs e)
{

}

我想在输入所有值后从文本文件计算txtModMark的平均值。它会在按钮4下面,所以当我点击它时,它会计算出来。我需要知道如何跳过每行的前几列并进入最后一列来执行平均计算。

1 个答案:

答案 0 :(得分:0)

从文件中读取然后解析它然后转换为INT,然后使用下面的List<int>直接计算平均值时,有什么意义:

List<int>

中声明Form
List<int> marks = new List<int>();

将标记存储在按钮点击事件

  private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            var WriteToFile = new System.IO.StreamWriter("student.txt"); //create textfile in default directory
            WriteToFile.Write(txtStudNum.Text + ", " + txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
            WriteToFile.Close();
           marks.Add(Convert.ToInt32(txtModMark.Text)); //add to list
        }

        catch (System.IO.DirectoryNotFoundException ex)
        {
            //add error message
        }
    }

在button4中,单击事件计算平均值

private void button4_Click(object sender, EventArgs e)
{
   int totalmarks = 0;
   foreach(int m in marks)
    totalmarks += m;

  MessageBox.Show("Average Is: " + totalmarks / marks.Count);
}
相关问题