java阶乘循环,使用循环来计算阶乘数,Java

I'm trying to compute the value of 7 factorial and display the answer, but when I tried to look up a way to do this I kept finding code that was written so that a number first had to be put in from the user and then it would factor whatever number the user put in. But I already know what number I need, obviously, so the code is going to be different and I'm having trouble figuring out how to do this.

I tried this at first

public class Ch4_Lab_7

{

public static void main(String[] args)

{

int factorial = 7;

while (factorial <= 7)

{

if (factorial > 0)

System.out.println(factorial*facto…

factorial--;

}

}

}

But all it does is display 7*7, then 6*6, then 5*5, and so on, and this isn't what I'm trying to do.

Does anyone know how to do it correctly?

解决方案

import java.util.Scanner;

public class factorial {

public static void main (String[] args) {

Scanner input = new Scanner(System.in);

//Gives Prompt

System.out.print("Enter a number to find the factorial of it");

//Enter the times you want to run

int number = input.nextInt();

//Declares new int

int factor = 1;

//Runs loop and multiplies factor each time runned

for (int i=1; i<=number; i++) {

factor = factor*i;

}

//Prints out final number

System.out.println(factor);

}

}

Just keep multiplying it and until it reaches the number you inputted. Then print.

Input:5

Output:120

input:7

Output:5040

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值