如何在Java中创建factorial并进行解释

时间:2017-03-07 13:48:49

标签: java factorial

问候互联网的人们!

我是Java的新手。我有一个关于创建阶乘的问题。

我能够创建一个只显示结果的阶乘。我在这里有语法:

import java.util.Scanner;

public class DynamicFact {
public static void main(String[] args){

    Scanner sc = new Scanner(System.in);
    int anc = 1;
    double fact = 1;
    System.out.println("Enter your number : ");
    int num = sc.nextInt();

    if (num < 0) {
        System.out.println("Your number is not valid. Please enter another number.");
    } else {
        for (anc = 1; anc <= num; anc++) {
            fact = fact * anc;
        }
        System.out.println("Factorial " + num + " is = " + fact );
    }

}
}

输出为(例如数字为6):因子6 = 720.0

但有人可以帮助我使输出看起来像这样: 因子6是6 * 5 * 4 * 3 * 2 * 1 = 720.0。 或者如果用户想要数字7,输出将是: 因子7是7 * 6 * 5 * 4 * 3 * 2 * 1 = 5040.0

等等。

非常感谢您的帮助。非常感谢你。

3 个答案:

答案 0 :(得分:1)

使用StringBuilder构建算术表达式:

} else {
    StringBuilder sb = new StringBuilder();
    for (anc = 1; anc <= num; anc++) {
        if(anc > 1)sb.append(" * ");
        sb.append(anc);
        fact = fact * anc;
    }
    sb.append(" = ").append(fact);
    System.out.println("Factorial " + num + " is " + sb);
}

答案 1 :(得分:0)

您可以使用的简单解决方案:

String result = "", separator = "";
for (anc = 1; anc <= num; anc++) {
    fact = fact * anc;
    result = anc + separator + result;
    separator = " * ";
}
System.out.println("Factorial " + num + " is " + result + " = " + fact);

这将显示6 Factorial 6 is 6 * 5 * 4 * 3 * 2 * 1 = 720.0

答案 2 :(得分:0)

import java.util.Scanner;
public class test {
public static void main(String[] args){

    Scanner sc = new Scanner(System.in);
    int anc = 1;
    double fact = 1;

    StringBuffer result = new StringBuffer();
    System.out.println("Enter your number : ");
    int num = sc.nextInt();

    if (num < 0) {
        System.out.println("Your number is not valid. Please enter another number.");
    } else {
        for (anc = 1; anc <= num; anc++) {
            fact = fact * anc;
            result.insert(0,Integer.toString(anc)+"*");
        }

        System.out.println("Factorial " + num + " is = " + fact );
        System.out.println(result.substring(0,result.length()-1));
    }

}
}