从文本文件C#计算平均值 [英] Calculate Average from a Textfile C#
问题描述
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下方,因此当我单击它时,它将进行计算.我需要知道如何跳过每行的前几列并转到最后一列以执行平均计算.
I want to calculate the average for txtModMark from the textfile once all the values have been entered. It will go under button 4 so when I click it, it calculates. I need to know how to skip the first few columns per row and get to the last column to perform the average calculation.
推荐答案
从文件中读取然后解析它,然后转换为INT
,然后在可以直接使用s List<int>
进行计算时计算平均值,这有什么意义?下方:
What's the point in reading from file then parse it and then convert to INT
and then calculate average when you can do it directly using s List<int>
like below:
在您的Form
List<int> marks = new List<int>();
将标记存储在按钮单击事件中
Store the marks in button click event
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点击事件中计算平均值
In button4 click event calculate the average
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);
}
这篇关于从文本文件C#计算平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!