在java中打印阶乘计算过程 [英] print factorial calculation process in java
本文介绍了在java中打印阶乘计算过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨我需要打印析因计算过程。
例如如果用户输入为5,系统应打印出5 * 4 * 3 * 2 * 1 = 120
Hi I need to print process of factorial calculation. E.g. If the user's input is 5, the system should print out "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。所以结果也是错误的。
如何更改代码?
谢谢
But the output is "1 * 2 * 3 * 4 * 5 * = 6". So the result is wrong too. How can I change the code? Thanks
推荐答案
问题是你没有在你的for语句上加上大括号{}
The problem is that you didn't put braces {} on your for statement:
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循环):
Also, if you're concerned about the order (1,2,4,5 instead of 5,4,3,2,1) you could do the following (changing the for loop):
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();
}
这篇关于在java中打印阶乘计算过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文