任何人都可以帮助我的java因子分配吗?我认为我做得对,但我不确定。我需要让用户输入一个数字,然后计算输入数字的阶乘。就像人输入10一样,用户会将此视为输出: 0! = 1,1! = 1,2! = 2,3! = 6,4! = 24,5! = 120,6! = 720,7! = 5040,8! = 40320,9! = 362880
import java.lang.Math;
import java.util.Scanner;
public class Factorial {
public static int factorial( int iNo ) {
if (iNo < 0) throw
new IllegalArgumentException("iNo must be >= 0");
int factorial = 1;
for(int i = 2 ; i <= iNo; i++)
factorial *= i;
System.out.println ( i + "! = " + factorial(i));
return factorial ;
}
}
public class Factorial{
public static void main ( String args[] ){
Scanner input = new Scanner (System.in);
System.out.println("Enter number of factorials to calculate: " );
int iNo = input.nextInt();
for(int i = 0; i <= iNo; i++)
factorial *= i;
System.out.println ( i + "! = " + factorial(i));
}
}
答案 0 :(得分:6)
你快到了。您遗失了main
中的一些代码:
System.out.println
。int
。您可以使用Scanner.nextInt
。for
循环,其变量i
从0
变为用户输入的数字。System.out.println(i + "! = " + factorial(i))
。完成上述四个步骤后,您就完成了!
答案 1 :(得分:-1)
这很好,但你不需要}
。
import java.lang.Math;
public class Factorial {
public static int factorial( int iNo ) {
// Make sure that the input argument is positive
if (iNo < 0) throw
new IllegalArgumentException("iNo must be >= 0");
// Use simple look to compute factorial....
int factorial = 1;
for(int i = 2; i <= iNo; i++)
factorial *= i;
return factorial;
}
public static void main ( String args[] ) {
}