java输出阶乘,在java中打印阶乘计算过程Hi I need to print process of factorial calculation.
< If the user's input is 5, the system should print out "5 * 4 * 3 * 2 * 1 = 120"
I have this code:
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();
}
}
I have tried insert this code:
System.out.print(count+" * ");
idea快捷键stream流循环
But the output is "1 * 2 * 3 * 4 * 5 * = 6". So the result is wrong too.
How can I change the code?
Thanks
小米发布会2022年时间表解决⽅案
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();
}噬肉菌生存环境
java下载过程
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--)
borderline什么意思{
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();
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。