繁体   English   中英

使用for循环的Java方法

[英]Java method using a for loop

我正在学习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;

  }
}

您的代码中实际上存在很多问题:

  • 使其成为实例方法没有任何意义。
  • 您尚未将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;

您缺少初始化。 现在,我将默认值添加到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;

  }
 }

您没有初始化总计,因此为0。每将0乘以任何值,您将得到0。

public int total = 1;

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

        }
        return total;

    }

您还没有初始化总计。 它的默认值为0。然后,当您将总数乘以任意值时,结果为0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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