使用for循环的Java方法
我正在学习Java,发现一点知识是令人困惑的。 目标是编写一个相当于n!作用我使用for循环乘以在方法外部声明的变量。我得到的只是0 我做错了什么使用for循环的Java方法,java,for-loop,methods,Java,For Loop,Methods,我正在学习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;
//
// 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;
}
}
您缺少初始化。现在,我将默认值添加到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;
}
}
公共类MathUtil
{
公共整数合计=1;
公共int产品(int n)
{
对于(int i=1;i您没有初始化total,因此它是0。无论何时将0与任何值相乘,结果都是0。您的代码中实际上有很多问题:
- 将其作为实例方法是没有意义的
- 您尚未将
总数
初始化为合理的值
- 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;
}
}
public int total=1;
公共int产品(int n){
for(inti=1;我读了这行代码,并告诉我它有什么问题:for(inti=1;i==n;i++)
提示:初始化、条件、递增。总计未使用值初始化。@kirbyquerbyIrrelevant@Kon.不,不是的,lmao。请学习一些基本的调试技巧。学习使用调试器,或者至少在一些有意义的位置打印信息。你应该能够自己轻松地解决问题。我确实纠正了它。N现在应该没问题,因为你从1到N。请添加一些解释,而不仅仅是解决它并发布代码。另外,产品从一开始就是一个坏名字。它没有恰当地描述功能。factorial
会是一个更好的名字,因为它实际上就是这样做的。@Bryan是的!我正计划提到它太好了!不知道为什么我最后错过了。谢谢你提醒我最后一位是聪明的!我可能会用它!我从来没有考虑过使用交换属性来做相反的乘法。我一直都是通过计数来做阶乘的。不过,记下增量前后的区别可能会有帮助,因为你的压缩解决方案取决于它,而for循环则不然。
result = n;
while (--n > 0) {
result *= n;
}
return result;
public int total = 1;
public int product(int n) {
for (int i = 1; i <= n; i++) {
total = total * i;
}
return total;
}