gpt4 book ai didi

使用 for 循环的 Java 方法

转载 作者:行者123 更新时间:2023-12-01 07:03:07 25 4
gpt4 key购买 nike

正在学习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 循环中的条件错误
  • 没有为方法指定有意义的名称
  • 凌乱的缩进
  • (列表不断增长...)

这是一个稍微改进的版本

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;

关于使用 for 循环的 Java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35931748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com