使用循环来计算阶乘数,Java [英] Using loops to compute factorial numbers, Java

查看:247
本文介绍了使用循环来计算阶乘数,Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算7阶乘的值并显示答案,但是当我试图查找一种方法来执行此操作时,我一直在查找编写的代码,以便首先必须从用户,然后它会考虑用户输入的任何数字。但是我已经知道我需要什么数字,显然,所以代码会有所不同,我无法弄清楚如何做到这一点。

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.

我最初试过这个

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--;
        }
    }
}

但它只是显示7 * 7,然后是6 * 6,然后是5 * 5,依此类推,这不是我想要做的。
有谁知道如何正确地做到这一点?

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.

输入:5
输出:120

Input:5 Output:120

输入:7
输出:5040

input:7 Output:5040

这篇关于使用循环来计算阶乘数,Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆