gpt4 book ai didi

java - 应用函数方法(调用函数)求阶乘

转载 作者:行者123 更新时间:2023-12-02 05:19:11 25 4
gpt4 key购买 nike

public static void main (String args [])  {
Scanner sc = new Scanner(System.in);
int number;
int factor=1;
System.out.println("Enter a number to find the factorial of it: ");
number= sc.nextInt();
factor=factorial(number);
if (number < 1 || number > 10)
{
System.out.println("Invalid!! the number has to be between 1 and 10");
}
System.out.println("The factorial of "+number+" is = " +factor);
}

public static int factorial (int number) {
int result = 1;
if (number < 1 || number > 10)
{
System.out.println("Invalid!! the number has to be between 1 and 10");
}
else {
for(int x=1; x<=number; x++ ) {
result= result*x;
}
}
return result;
}

我的代码工作正常,但如果我输入 11,它会显示无效消息,并且还会计算我不想要的 11 的阶乘。

最佳答案

您应该移动检查用户输入范围的代码,使其位于对 factorial() 函数的调用之上:

public static void main (String args [])  {
Scanner sc = new Scanner(System.in);
int number;
int factor=1;
System.out.println("Enter a number to find the factorial of it: ");
number= sc.nextInt();
if (number < 1 || number > 10) {
System.out.println("Invalid!! the number has to be between 1 and 10");
} else {
factor=factorial(number);
System.out.println("The factorial of "+number+" is = " +factor);
}
}

请注意,对 factorial() 的调用和 println() 语句现在都位于新的 else block 内。因此,如果用户输入无效数字,程序给出的唯一响应就是错误消息。

如果您还想在 factorial() 中进行错误检查,最清晰的方法可能是抛出 IllegalArgumentException当给出无效输入时:

public static int factorial (int number) {
int result = 1;
if (number < 1 || number > 10)
{
System.out.println("Invalid!! the number has to be between 1 and 10");
throw new IllegalArgumentException("Factorial input has to be between 1 and 10");
}

// rest of your code....
}

关于java - 应用函数方法(调用函数)求阶乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26640604/

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