【问题标题】:My average result is adding 1 to the correct answer我的平均结果是正确答案加 1
【发布时间】:2018-12-05 11:46:44
【问题描述】:

我完全没有编码经验,但我正在尝试帮助学生编写一个程序,该程序旨在显示用户放置在数组中的数字的平均值。

它给了我们正确的平均结果,但是加了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;
         }
}

【问题讨论】:

  • double dblTotal = 0; 不是double dblTotal = intRecordCount;
  • double dblTotal = intRecordCount; 看起来很奇怪 - 你为什么从这个数字开始?根据您的描述,您想要数组中数字的平均值,为什么要向其中添加元素的数量?
  • 欢迎来到 Stack Overflow。这不是让其他人调试您的代码的地方。首先阅读tourHow to Askedit 您的问题,以显示一些示例输入、预期输出和实际输出,并表明您已使用调试器在程序的每一步检查您的变量。你怀疑的那一行没有错。

标签: c# arrays average


【解决方案1】:

我宁愿在上下文中使用 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;   
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 2022-11-13
    相关资源
    最近更新 更多