简体   繁体   中英

How do I calculate the average

Im able to get the sum in dataGridView but having trouble on properly getting the average.

foreach (DataGridViewRow row in dataGridView.Rows) {
    row.Cells["Average"].Value = Convert.ToDouble(row.Cells[4].Value) +
    Convert.ToDouble(row.Cells[5].Value) +
    Convert.ToDouble(row.Cells[6].Value);
}

The average is the sum of the elements divided by the total number of elements. In your case, since there are total of three elements, you'll have to divide the sum by three.

You are not doing an average calculation but a sum calculation. Simply divide the total by the number of values provided to find the average:

foreach (DataGridViewRow row in dataGridView.Rows)
                    row.Cells["Average"].Value = (Convert.ToDouble(row.Cells[4].Value) + Convert.ToDouble(row.Cells[5].Value) + Convert.ToDouble(row.Cells[6].Value)) / 3;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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