在java中打印阶乘计算过程

时间:2014-01-15 23:06:46

标签: java if-statement factorial

嗨我需要打印析因计算过程。 例如。如果用户输入为5,系统应打印出“5 * 4 * 3 * 2 * 1 = 120”

我有这段代码:

 public static void factorial()
{
    Scanner sc = new Scanner(System.in);
    int factorial = 1;
    int count;

    System.out.println(me+", This is option 2: Calculate a factorial");
    System.out.print("Enter your number: ");
    int number = sc.nextInt();
    System.out.println();

    if (number>0)
        {
            for (count=1; count<=number; count++)

            factorial = factorial*count;

            System.out.println(" = "+factorial);
            System.out.println();
        }
    else
    {
        System.out.println("Enter a positive whole number greater than 0");
        System.out.println();
    } 

}    

我试过插入此代码:

 System.out.print(count+" * ");

但输出为“1 * 2 * 3 * 4 * 5 * = 6”。所以结果也是错误的。 我该如何更改代码? 感谢

3 个答案:

答案 0 :(得分:4)

问题是您没有在for语句中添加大括号{}

if (number>0)
{
    for (count=1; count<=number; count++)
    {
        factorial = factorial*count;
        System.out.print(count);
        if(count < number)
            System.out.print(" * ");
    }

    System.out.println("Factorial of your number is "+factorial);
    System.out.println();
}

此外,如果您担心订单(1,2,4,5而不是5,4,3,2,1),您可以执行以下操作(更改for循环):

if (number>0)
{
    for (count=number; count>1; count--)
    {
        factorial = factorial*count;
        System.out.print(count);
        if(count > 2)
            System.out.print(" * ");
    }

    System.out.println("Factorial of your number is "+factorial);
    System.out.println();
}

答案 1 :(得分:4)

使用此代码。它会检查您是否在最后一次迭代中,否则添加" * "

System.out.print(count + ((count < number) ? " * " : ""));

否则你也可以使用:

for (count=1; count < number; count++) { // Note: < instead of <=
    factorial *= count;
    System.out.print(count + " * ");
}
factorial *= number;
System.out.println(number + " = " + factorial);

答案 2 :(得分:1)

这样的事情应该能够实现您的目标:

        int number = 5;
        int factorial = 1;
        String factString = "";
        for (int count = number; count > 0; count--) {
            factorial = factorial * count;
            if (count == number) {
                factString += count;
            } else {
                factString += " * " + count;
            }
        }

        System.out.println("Factorial of " + factString + " is " + factorial);
        System.out.println();

代码将从输入的数字开始倒计时。这将通过将您的进度存储在一个字符串中来打印所有行。