首页 > 解决方案 > 阶乘静态法

问题描述

我正在使用静态方法进行阶乘计算我已经能够使其一次使用一个 int 但扫描仪需要能够采用两个ints(N 和 M),其中代码执行所有数字的阶乘N 到 M。

到目前为止,这是我的代码

import java.util.Scanner;
public class Factorial {

  public static long Factorialcalc(int n) {
    long fact = 1;
    for (int i = 1; i <= n; i++) {
      fact *= i;
    }
    return fact;
  }
  public static void main(String args[]) {
    System.out.println("Enter first int N");
    Scanner sc = new Scanner(System.in);
    int n;
    long fact = 1;
    n = sc.nextInt();
    System.out.println("Enter second int M");
    int m;
    m = sc.nextInt();
    if (n < 0) {
      System.out.println("Not Valid!");
    } else {
      for (int i = n; i <= m; i++) {
        fact = Factorialcalc(i);
      }
      fact = Factorialcalc(n);
      System.out.println("the factorial for " + n + " is " + fact + ".");
    }
  }
}

我不确定我应该如何添加 M int 以计算从 N 向上的阶乘。

标签: javastatic-methods

解决方案


main方法中需要进行以下更改:

int m = sc.nextInt()

在其他块中:

for (int i=n;i<=m;i++){
    fact = Factorial.Factorialcalc(i);

}

提示:始终将您的代码添加为代码示例或片段 (HTML/CSS/JS)


推荐阅读