将 2 个数字作为输入并找到这些数字的阶乘以及介于两者之间的每个数字的程序?



这段代码应该取2个数字,并找到每个数字之间的阶乘。但是,我没有得到正确的输出,也无法弄清楚我做错了什么。

Scanner scan = new Scanner(System.in);
long result = 1;
int m = scan.nextInt();
int n = scan.nextInt();
scan.close();
if (n > 0 && m > 0)             //want factorial greater than zero
for(int j = n; j <= m; j++)
{
for(int i = 1; i <= j; i++)
{
result = result * i;    //find factorial
}
System.out.println(result);
}
if(n <= 0 || m <= 0)        //if value is les than zero
{
System.out.println("Not Valid!");
}

类似的东西应该有效:

public class RangeFactorial {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int max = scan.nextInt();
int min = scan.nextInt();
if (max < 0 || min < 0) {
System.out.println("Invalid Params");
}
for (int i = min; i <= max; i++) {
System.out.println("Factorial for " + i + " is: " + factorial(i));
}
scan.close();
}
private static int factorial(int i) {
if (i <= 1) {
return 1;
}
return i * factorial(i-1);
}
}

请注意,代码假定最大/最小值已到位,我省略了从给定输入中确定最大/最小整数的逻辑。您需要添加此内容。

您忘记将"结果"重置为 1。

此外,如果它只是检查第一个的否定,则不需要另一个 if 语句,只需使用 else。

我还修复了代码样式指南以遵循标准的Java指南,如下所示:

  1. 您使用的花括号样式是 C/C++ 中常用的样式。
  2. 即使 if 语句或循环后面只包含一行,在 Java 中使用大括号也是很好的礼节。

如果您想了解更多信息,请查看 Google Java 风格指南。

Scanner scan = new Scanner(System.in);
long result = 1;
int m = scan.nextInt();
int n = scan.nextInt();
scan.close();
if (n > 0 && m > 0){
for(int j = n; j <= m; j++){
result = 1; //You forgot to reset 'result'
for(int i = 1; i <= j; i++){
result *= i;   
}
System.out.println(result);
} else { // No need for another if statement
System.out.println("Not Valid!");
}

最新更新