嗨,我需要计算存储在数据库中的10个整数的平均值。
这是我到目前为止所做的。
private void getAverage()
{
StudentsDataSet.StudentsRow courseMarks = studentsDataSet.Students.Course[10];
average = 0;
int[] array;
for (int index = 0; index < 10 ; index++)
{
average += array[index];
}
average = average / 10;
averageBox.Text = average.ToString();
}
正如你所看到的,我不知道我在做什么...任何指针??
答案 0 :(得分:1)
您的代码存在一些问题,我将逐一解决:
studentsDataSet.Students.Course[10]
)获取数据。那可能不是你想要的。for
循环和平均值的除数)。当课程数量发生变化时,这将成为错误的来源。average
应该是sum
(这就是它实际存储的内容)而array
是一个糟糕的选择,因为它没有描述变量的内容,而是它的格式。这是一些可以完成这项工作的代码。我添加了评论以准确解释发生了什么:
//The method that will add the average to the text box. You need to provide the row index.
//One common way to get the row index would be the SelectedIndex of your data grid
private void GetAverage(int rowIndex)
{
//Get the row whose data you want to process
DataRow courseMarks = studentsDataSet.Students.Rows[rowIndex];
//Initialize an array with the names of the source columns
string[] courseColumnNames = { "Course1", "Course2", "Course3", "Course4", "Course5",
"Course6", "Course7", "Course8", "Course9", "Course10" };
//Declare and initialize the array for the marks
int[] markValues = new int[courseColumnNames.Length];
//Fill the array with data
for (int index = 0; index < courseMarks.Length ; index++)
{
//Get the column name of the current course
string columnName = courseColumnNames[index];
//Copy the column value into the array
markValues[index] = (int)courseMarks[columnName];
}
//Calculate the sum
int sum = 0;
for (int index = 0; index < courseMarks.Length ; index++)
{
sum += markValues[index];
}
//Calculate the average from the sum
//Note: Since it's an integer division there will be no decimals
int average = sum / courseMarks.Length;
//Display the data
averageBox.Text = average.ToString();
}
请注意,您当然可以将两个循环合并为一个(甚至删除数组,因为您可以直接添加到sum
变量)。我没有这样做,以保持过程的每一步明确分开。您也可以使用LINQ方法Average
,但这很不容错过。
答案 1 :(得分:0)
您可以执行以下操作:
int average = studentsDataSet.Students.Course.Average();
您必须添加using System.Linq;
才能生效。
答案 2 :(得分:0)
您可以尝试以下操作代替所有代码:
private double GetAverage()
{
StudentsDataSet.StudentsRow courseMarks = studentsDataSet.Students.Course[10];
var average=courseMarks.Average(x =>(double) x["*YourDataColumnName*"]);
return average;
}
YourDataColumnName 是您的行的列,其中包含您希望获得该值的平均值