英文:
Java function multiplying itself while printing?
问题
我是Java的新手,我有一个问题。我创建了一个计算n的阶乘的类:
public class factorial {
double result=1;
public double equation (int x){
for (int i=1;i<x+1;i=i+1) {
result = result*i;
}
return result;
}
}
我知道我漏掉了当x=0的情况,但这不是重点。无论我在其他类中将其打印出来,它似乎都在自己乘以自己:
public class task1 {
factorial fa = new factorial();
void printit(){
System.out.println(fa.equation(3));
System.out.println(fa.equation(3));
System.out.println(fa.equation(3));
}
}
主类:
public class Main {
public static void main(String[] args) {
task1 ta = new task1();
ta.printit();
}
}
输出:
6.0
36.0
216.0
我应该如何做才能使其打印出三次的是6,而不是一直在自我相乘?
英文:
I'm new to Java and I have a problem. I created a class that calculates factorial of n:
public class factorial {
double result=1;
public double equation (int x){
for (int i=1;i<x+1;i=i+1) {
result = result*i;
}
return result;
}
}
I know I'm missing the case when x=0 but that's not the point Whenever I print it in other class it seems to multiply by itself
public class task1 {
factorial fa =new factorial();
void printit(){
System.out.println(fa.equation(3));
System.out.println(fa.equation(3));
System.out.println(fa.equation(3));
}
}
Main class:
public class Main {
public static void main(String[] args) {
task1 ta = new task1();
ta.printit();
}
}
Output:
6.0
36.0
216.0
How should I do it so it prints 6 three times instead of multiplying by itself
答案1
得分: 1
你需要在equation
方法内部声明result
变量。这样,每当你运行equation
方法时,变量result
都是新的。
public class Factorial {
public double equation(int x) {
double result = 1;
for (int i = 1; i < x + 1; i = i + 1) {
result = result * i;
}
return result;
}
}
如果不这样做,那么变量result
将保持与Factorial
实例相同。另外请注意,Java类名通常以大写字母开头,所以应该使用Factorial
代替factorial
。
你可以使用i++
或i += 1
来替代i = i + 1
。类似地,你可以使用result *= i
来替代result = result * i
。
一些示例:
i = i + 10 == i += 10
i = i - 10 == i -= 10
i = i * 10 == i *= 10
i = i / 10 == i /= 10
i = i % 10 == i %= 10
i = i + 1 == i += 1 == i++
i = i - 1 == i -= 1 == i--
英文:
You have to declare result
inside the method equation
. This way, the variable result
is fresh whenever you run the method equation
.
public class factorial {
public double equation (int x){
double result = 1;
for (int i = 1; i < x + 1; i = i + 1) {
result = result * i;
}
return result;
}
}
If you don't do this, then the variable result
stays the same with that instance of factorial
. Also note that Java class names usually start with a capital letter, so instead of factorial
, it would be Factorial
.
Instead of i = i + 1
, you can use i++
or i += 1
. Similarly, instead of result = result * i
, you can do result *= i
.
Some examples:
i = i + 10 == i += 10
i = i - 10 == i -= 10
i = i * 10 == i *= 10
i = i / 10 == i /= 10
i = i % 10 == i %= 10
i = i + 1 == i += 1 == i++
i = i - 1 == i -= 1 == i--
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论