本文介绍了Java阶乘格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的阶乘方法可以正常工作,尽管我想仅通过输出数字和阶乘结果来更改输出.例如,我希望用户输入6来表示6 * 5 * 4 * 3 * 2 * 1 = 720,而不是6的阶乘是:720.

My factorial method is working correctly although I would like to change the output from just outputting the number and the factorial result. For example I would like if the user enters 6 for the output to say 6 * 5 * 4 * 3 * 2 * 1 = 720, instead of factorial of 6 is: 720.

int count, number;//declared count as loop and number as user input
    int fact = 1;//declared as 1
    Scanner reader = new Scanner(System.in);  // Reading from System.in
    System.out.println("Please enter a number above 0:");
    number = reader.nextInt(); // Scans the next token of the input as an int
    System.out.println(number);//prints number the user input
    if (number > 0) {
        for (i = 1; i <= number; i++) {//loop 
            fact = fact * i;
        }
        System.out.println("Factorial of " + number + " is: " + fact);
    }
    else 
    {
        System.out.println("Enter a number greater than 0");
    }
}

推荐答案

看看这种递归方法:(自己检查负数:D)

Check out this recursive approach: (check negative numbers yourself :D)

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int num = scanner.nextInt();
    System.out.println(getFactorialString(num, " = " + getFactorial(num)));
}

public static String getFactorialString(int num, String result) {
    if (num == 0) return "0 => 1";
    if (num == 1) {
        result = "" + num + "" + result;
    } else {
        result = getFactorialString(num - 1, result);
        result = "" + num + " x " + result;
    }
    return result;
}

public static int getFactorial(int num) {
    if (num == 0) return 1;
    return num * getFactorial(num - 1);
}

这篇关于Java阶乘格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 02:34