编写程序计算 N! /K!对于给定的 N 和 K.in Java - 溢出问题
Write a program that calculates N! / K! for given N and K.in Java - overflow problem
import java.util.Scanner;
public class CalculateAgain {
public static void main (String[] Args) {
Scanner input = new Scanner(System.in);
long N = input.nextLong();
long K = input.nextLong();
double result = 1;
while ( N > K) {
result*=N;
N--;
}
System.out.printf("%.0f", result);
}
}
我无法打印大阶乘数字。我已经尝试了很长时间的变量结果,但是当我 println
它时,我得到了错误的结果。
我也尝试过使用 BigDecimal,但我无法将其转换为 long 或 double。
我是个初学者——我学过循环、数组、条件语句。我对方法一窍不通
使用import java.math.BigInteger;
在扫描仪之后尝试这种方式。假设我使用的是 BigInteger
,您可以根据您的要求进行更改。
int n = Integer.parseInt(scanner.nextLine());
int k = Integer.parseInt(scanner.nextLine());
BigInteger result = new BigInteger("1");
int range = n - k;
for (int i = range; i > 0; i--) {
result = result.multiply(new BigInteger(String.valueOf(n)));
n--;
}
import java.util.Scanner;
public class CalculateAgain {
public static void main (String[] Args) {
Scanner input = new Scanner(System.in);
long N = input.nextLong();
long K = input.nextLong();
double result = 1;
while ( N > K) {
result*=N;
N--;
}
System.out.printf("%.0f", result);
}
}
我无法打印大阶乘数字。我已经尝试了很长时间的变量结果,但是当我 println
它时,我得到了错误的结果。
我也尝试过使用 BigDecimal,但我无法将其转换为 long 或 double。
我是个初学者——我学过循环、数组、条件语句。我对方法一窍不通
使用import java.math.BigInteger;
在扫描仪之后尝试这种方式。假设我使用的是 BigInteger
,您可以根据您的要求进行更改。
int n = Integer.parseInt(scanner.nextLine());
int k = Integer.parseInt(scanner.nextLine());
BigInteger result = new BigInteger("1");
int range = n - k;
for (int i = range; i > 0; i--) {
result = result.multiply(new BigInteger(String.valueOf(n)));
n--;
}