Dar*_*ani 0 java loops factorial
我正在尝试计算7阶乘的值并显示答案,但是当我试图查找一种方法来执行此操作时,我不断查找编写的代码,以便首先必须从用户输入一些数字,然后它会考虑用户输入的任何数字.但是我已经知道我需要什么数字了,所以代码会有所不同,我无法弄清楚如何做到这一点.
我一开始就尝试过这个
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--;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它所做的只是显示7*7,然后是6*6,然后是5*5,依此类推,这不是我想要做的.有谁知道如何正确地做到这一点?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
只需保持乘以它直到它达到你输入的数字.然后打印.
输入:5输出:120
输入:7输出:5040