gpt4 book ai didi

java - 如何在java中使用循环计算阶乘

转载 作者:行者123 更新时间:2023-11-30 02:51:49 26 4
gpt4 key购买 nike

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

对我的方法有建议吗?或者有更好的使用循环的方法吗?谢谢!

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);
}
while (number <= 0);{
System.out.println("That's not a positive integer!");
}

System.out.print(factTotal);
}

}

最佳答案

这就是我处理问题的阶乘部分的方法。我会取消 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");
}

关于java - 如何在java中使用循环计算阶乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38416999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com