如何在控制台中找到阶乘并显示计数结果? [英] How to find factorial and show result of counting in console?
本文介绍了如何在控制台中找到阶乘并显示计数结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(n+"!="+factorial(n));
}
public static int factorial(int num) {
return (num == 0) ? 1 : num * factorial (num - 1);
}
}
如何使此代码在控制台3! = 1*2*3 = 6
中发短信?
how make this code to text in console 3! = 1*2*3 = 6
?
推荐答案
请勿为此使用递归.此外,它并不是真正有效或必要的.
Don't use recursion for this. Besides, it isn't really efficient or necessary.
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int fact = 1;
String s = n + "! = 1";
for (int i = 2; i <= n; i++) {
fact *= i;
s += "*" + i;
}
s += " = ";
System.out.println(s + fact);
这篇关于如何在控制台中找到阶乘并显示计数结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文