【问题标题】:Java method using a for loop使用 for 循环的 Java 方法
【发布时间】:2016-03-11 03:38:12
【问题描述】:

我正在学习 Java,发现一点点知识都令人困惑。 目标是编写一个等效于 n! 的方法。功能。我正在使用 for 循环来乘以在方法外部声明的变量。我得到的只是 0。

我做错了什么?

//
// Complete the method to return the product of
// all the numbers 1 to the parameter n (inclusive)
// @ param n
// @ return n!

public class MathUtil
{
   public int total;

   public int product(int n)
  {
   for (int i = 1; i == n; i ++)
   {
       total = total * i;

    }
    return total;

  }
}

【问题讨论】:

  • 阅读这行代码并告诉我它有什么问题:for (int i = 1; i == n; i ++) 提示:初始化、条件、增量。
  • Total 未用值初始化。
  • @kirbyquerby 无关
  • @Kon。不,不是,lmao。
  • 请学习一些基本的调试技巧。学习使用调试器,或者至少在一些有意义的位置打印出信息。您应该能够自己轻松解决问题

标签: java for-loop methods


【解决方案1】:

其实你的代码有很多问题:

  • 使它成为实例方法没有意义。
  • 您尚未将total 初始化为合理的值。
  • for 循环中的条件错误
  • 方法没有给出有意义的名称
  • 凌乱的缩进
  • (列表不断增加...)

所以这里有一个稍微改进的版本

public class MathUtil
{
  //
  // Complete the method to return the product of
  // all the numbers 1 to the parameter n (inclusive)
  // @ param n
  // @ return n!

  public static int factorial(int n)
  {
    int total = 1;
    for (int i = 1; i <= n; i ++)
    {
      total = total * i;
    }
    return total;
  }
}

这样您就可以将其称为MathUtil.product(123) 而不是一些奇怪的new MathUtil().product(123)

我个人更愿意做类似的事情

result = n;
while (--n > 0) {
    result *= n;
}
return result;

【讨论】:

  • 另外,产品一开始就是个坏名声。它没有适当地描述功能。 factorial 会是一个更好的名字,因为它实际上是这样做的。
  • @Bryan 是的!我也打算提这个!不知道为什么我最后错过了。谢谢提醒
  • 最后一点很聪明!我可以用那个!我从来没有考虑过使用交换属性来做反向乘法。我总是通过计数来做阶乘。不过,对 pre 与 post 增量之间的区别做一个小记录可能会有所帮助,因为您的紧凑解决方案取决于它,而 for 循环则没有。
【解决方案2】:

您缺少初始化。现在我将默认值添加到 1。您还必须更改条件。只要 var i 小于或等于 n,for 循环就必须继续。

public class MathUtil
{
  public int total = 1;

  public int product(int n)
  {
    for (int i = 1; i <= n; i ++)
    {
     total = total * i;
    }
   return total;

  }
 }

【讨论】:

  • 我确实纠正了它。现在应该没问题了,因为你从 1 到 N。
【解决方案3】:

你没有初始化总计,因此它是 0。每当你将 0 与任何东西相乘时,你都会得到 0 作为结果。

【讨论】:

    【解决方案4】:
    public int total = 1;
    
        public int product(int n) {
            for (int i = 1; i <= n; i++) {
                total = total * i;
    
            }
            return total;
    
        }
    

    你还没有初始化总计。它默认为 0。然后当你将任何东西与总数相乘时,你会得到 0 作为结果

    【讨论】:

    • 请添加一些解释,而不是仅仅解决它并发布代码
    猜你喜欢
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 2017-09-12
    • 1970-01-01
    相关资源
    最近更新 更多