[英]Returning the factorial of 10 using recursion in java
Hello I have written the following code to return the factorial of n when the the value is 10 but i cant get my program to work.您好,我编写了以下代码以在值为 10 时返回 n 的阶乘,但我无法使我的程序正常工作。 I have never used Java before and I am a beginner.我以前从未使用过 Java,我是初学者。
public static int Factorial(n)
{
if (n == 0) {
return 1;
} else {
return( n * Factorial(n-1) );
}
}
public static int main(args) {
System.out.println(Factorial(10));
}
You lack a few type definitions and the required main method.您缺少一些类型定义和所需的 main 方法。 Your class should look like this to work:你的类应该像这样工作:
public class Main {
public static int Factorial(int n) {
if (n == 0) {
return 1;
} else {
return(n * Factorial(n-1));
}
}
public static void main(String args[]) {
System.out.println(Factorial(10));
}
}
You could also try this:你也可以试试这个:
int factorial(int n)
{
return (n>=1 ? n * factorial(n-1) : 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.