我的java factorial赋值有问题

时间:2014-03-20 16:34:25

标签: java factorial

任何人都可以帮助我的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));


}
}

2 个答案:

答案 0 :(得分:6)

你快到了。您遗失了main中的一些代码:

  1. 提示用户输入数字。您可以使用System.out.println
  2. 阅读用户输入的int。您可以使用Scanner.nextInt
  3. 设置for循环,其变量i0变为用户输入的数字。
  4. 在循环体中调用System.out.println(i + "! = " + factorial(i))
  5. 完成上述四个步骤后,您就完成了!

答案 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[] ) {




    }