繁体   English   中英

来自datagridview中3列的汇总数量

[英]Aggregated number from 3 columns in datagridview

 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%。 我们还需要它来将其除以数组中对象的数量。 有没有人可以帮助我解决我的代码?

如果是我,我可能会创建一个班级来代表学生,并为它提供Name和每个考试分数的属性。 然后,我将添加一个属性,该属性根据百分比给出计算出的总得分。

接下来,我们可以基于DataGridView的数据填充这些Student对象的列表,然后可以很容易地显示聚合和班级平均值。

例如, 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM