java - 阶乘静态法
问题描述
我正在使用静态方法进行阶乘计算我已经能够使其一次使用一个 int 但扫描仪需要能够采用两个int
s(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 向上的阶乘。
解决方案
在main
方法中需要进行以下更改:
int m = sc.nextInt()
在其他块中:
for (int i=n;i<=m;i++){
fact = Factorial.Factorialcalc(i);
}
提示:始终将您的代码添加为代码示例或片段 (HTML/CSS/JS)
推荐阅读
- google-app-engine - 谷歌应用引擎给我的默认域名如何更改?
- android - 从服务安排时,Android 的 WorkManager 未运行
- javascript - 如何在 Node.js 进程窗口之外获取键盘输入?
- tkinter - 使用 Python 的 tkinter 将输入字段传输到 excel 文件
- java - 如何在 TextReport 和 BrowserWebDriverContainer 上替换 JUnit 5 中的 @Rule 注释?
- c# - 通过 asp .net core 连接到 Google api 导致无限的授权循环
- regex - 正则表达式写入以下模式,即匹配相同的字母数字字符任意次数
- python - Python Pandas 基于另一列值创建新列
- reactjs - TypeError:window.gtag 不是函数
- cassandra - 删除表后如何安全删除数据目录?