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. I have never used Java before and I am a beginner.
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. 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.