private void button4_Click(object sender, EventArgs e)
{
double sum = 0.3;
double sum1 = 0.4;
double sum2 = 0;
for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
{
sum = sum * int.Parse(dataGridView1.Rows[i].Cells[4].Value.ToString());
sum = sum * int.Parse(dataGridView1.Rows[i].Cells[5].Value.ToString());
sum1 = sum1 * int.Parse(dataGridView1.Rows[i].Cells[6].Value.ToString());
sum2 = sum1 + sum2;
}
textBox8.Text = sum2.ToString();
}
我想计算一个包含3个标记元素的加权总和的聚合标记。课程1为30%,课程2为30%,期末考试为40%。我们还需要它来将其除以数组中对象的数量。有没有人可以帮助我解决我的代码?
答案 0 :(得分:0)
如果是我,我可以创建一个班级来代表一个学生,并为它Name
和每个考试分数提供一个属性。然后,我将添加一个属性,该属性根据百分比给出计算出的总得分。
接下来,我们可以根据您的Student
中的数据填充这些DataGridView
对象的列表,然后可以很容易地显示汇总和类平均值。
例如,Student
类可能类似于:
public class Student
{
public string Name { get; set; }
public int Course1Score { get; set; }
public int Course2Score { get; set; }
public int FinalExamScore { get; set; }
public double AggregateScore => Course1Score * .3 + Course2Score * .3 +
FinalExamScore * .4;
}
然后我们可以填充它们的列表并输出结果:
private void button4_Click(object sender, EventArgs e)
{
var students = new List<Student>();
for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
{
students.Add(new Student
{
Name = $"student{i + 1}",
Course1Score = int.Parse(dataGridView1.Rows[i].Cells[4].Value.ToString()),
Course2Score = int.Parse(dataGridView1.Rows[i].Cells[5].Value.ToString()),
FinalExamScore = int.Parse(dataGridView1.Rows[i].Cells[6].Value.ToString()),
});
}
string results = string.Join(Environment.NewLine,
students.Select(s => $"{s.Name} had an aggregate score of {s.AggregateScore}"));
results += "\n\nThe average aggregated score is: " +
students.Average(student => student.AggregateScore);
MessageBox.Show(results);
}