我绝对没有编码经验,但是我正在尝试为学生提供一个程序,该程序旨在显示用户放置在数组中的平均数字。
它为我们提供了正确的平均结果,但是加了1 。我真的不明白他的代码中发生了什么,但是我觉得它已经到了这一行的结尾:
for (intLoopCount = 0; intLoopCount < intRecordCount; intLoopCount++)
任何帮助都将不胜感激,因为我不懂事。
完整的代码部分:
private static double AverageReading()
{
double dblAverage;
double dblTotal = intRecordCount;
if (intRecordCount == 0) //no books chosen
{
return 0;
}
else
{
int intLoopCount = 0;
for (intLoopCount = 0; intLoopCount < intRecordCount; intLoopCount++)
{
dblTotal = dblTotal + intLoanNumber[intLoopCount];
}
dblAverage = dblTotal / intRecordCount;
return dblAverage;
}
}
答案 0 :(得分:3)
我宁愿在上下文中使用 Linq (如果我们有Any
个项目返回其中的Average
个,否则返回0
):
private static double AverageReading() => intLoanNumber.Any()
? intLoanNumber.Average()
: 0.0;
如果您喜欢 loop 实现:
private static double AverageReading() {
if (intRecordCount == 0)
return 0.0;
double dblTotal = 0.0; // <- 0.0, not intRecordCount
// probably, condition should be "i < intLoanNumber.Length" not "i < intRecordCount"
for (int i = 0; i < intRecordCount; ++i)
dblTotal += intLoanNumber[i];
// probably, "dblTotal / intLoanNumber.Length" instead of "dblTotal / intRecordCount"
return dblTotal / intRecordCount;
}