如何用java中的循环计算阶乘

时间:2016-07-17 01:00:08

标签: java loops factorial

我试图编写一个程序的一部分,使用循环计算阶乘。我没有任何错误消息,但我没有得到任何输出。

我的方法是否有建议或是否有更好的方法使用循环?谢谢!

FlightInfo

}

3 个答案:

答案 0 :(得分:3)

这是我接近问题的阶乘部分的方式。我会取消do / while循环,因为如果你没有得到输出,你似乎陷入无限循环。

//Call this method when you want to calculate the factorial
public int factorial(int num){
   for(int i = num-1; i > 1; i--){
       num *= i;
   }
   return num;
}

这就是你的代码中的样子。

import java.util.Scanner;

public class Factorial {
public static void main(String[] args) {

    System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");

    //Create scanner object for reading user input
    Scanner input = new Scanner(System.in);

    //Declare variables
    int number = input.nextInt();
    int factTotal = 1;

    if(number > 0){

        factTotal = factorial(number);

        System.out.print(factTotal);
   }
   else
       System.out.println("This is a negative number");
}

答案 1 :(得分:0)

@Pernicious,请稍微修改一下您的程序并添加我的评论。我认为这就是你想要做的事情。

import java.util.Scanner;

public class Factorial {

public static void main(String[] args) {

    System.out.print("Enter a non-negative number that you wish to perform a     factorial function on: ");

    //Create scanner object for reading user input
    Scanner input = new Scanner(System.in);

    //Declare variables
    int number = input.nextInt();
    int factTotal = 1;

// The input number check should be before factorial calculation
    if(number <= 0){
        System.out.println("That's not a positive integer!");
        System.exit(0);
    }

    //Execute factorial
    do {
        factTotal = factTotal * number;
        number--;
// while (number >= 1); This while should be after do{}, not within do{}
    } while (number >= 1);
//        This check should be done immeduately after user input, not after calculation of factorial.
//        while (number <= 0);
//        {
//            System.out.println("That's not a positive integer!");
//        }

    System.out.println(factTotal);
 }
}

答案 2 :(得分:-1)

在您的代码中,在do...while循环中,您使用了此while语句:

while (number >= 1);

你没注意到分号吗?这个循环有什么意义呢?目前它导致无限循环,因为number的值永远不会改变,因此您没有输出。
另外,你的第二个while循环应该更像是if语句,如下所示 那段代码相当于:

while (number >= 1)
{
   //doNothing
}

我相信你的意思是:

import java.util.Scanner;

public class Factorial {
public static void main(String[] args) {

    System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");

    //Create scanner object for reading user input
    Scanner input = new Scanner(System.in);

    //Declare variables
    int number = input.nextInt();
    int factTotal = 1;

    //Execute factorial
    do{
        factTotal = factTotal * number;
        number--;
    }
    while (number <= 1);
    if(number < 0)
    {
         System.out.println("That is not a positive integer");
    }
    else
    System.out.print(factTotal);
}