Eqo*_*rip 2 java for-loop factorial
我想使用for循环在java中做一个阶乘程序。例如,我想接受用户输入,比如说10,然后乘以10*9*8*7*6*5*4*3*2*1。我需要帮助构建for循环。下面的代码是我目前所拥有的所有代码,因为我不知道该去哪里。
import java.util.Scanner;
import java.lang.Math;
public class factorial {
public static void main(String[] args) {
int num;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
num = input.nextInt();
}
}
Run Code Online (Sandbox Code Playgroud)
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
System.out.print("Enter a number: ");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
long factorialResult = factorialRecursive(num);
System.out.println(factorialResult);
}
public static long factorialRecursive(int n) {
if (n == 0 || n == 1 )
return 1;
return n * factorialRecursive(n - 1);
}
}
Run Code Online (Sandbox Code Playgroud)
如果数量很大,就会发生“stackoverflow”。