[英]The while and do-while loops The smallest value
我需要编写一个程序,让用户输入一个长正数 m。 我需要找出最小的整数 n 是多少,使得 n! > 米。
到目前为止,我已经编写了这样的代码:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
long number = scanner.nextLong();
int fact = 1;
int count =1;
while (fact <= number) {
count ++;
fact *=count;
}
System.out.println(count);
}
}
测试输入:6188989133 正确输出:13
您的代码输出:
我的代码输出是空的。 我在这里缺少什么?
您必须对fact
变量使用long
。 当您使用int
,可能的值介于-2,147,483,648
和2,147,483,647
之间。
但是,您永远不会超过输入数字6,188,989,133
,因此您的while(fact <= number)
循环永远不会退出。 每个可能的整数值都将小于6,188,989,133
。 这解释了为什么你的代码输出是“空的”,因为它没有到达System.out.println(count);
线。
请记住, long
类型也有这样的限制,值只能介于-9,223,372,036,854,775,808
和9,223,372,036,854,775,807
之间。 当输入数字那么大时,您将找不到大于输入的正确fact
值,因为您受到long
类型值范围的限制。 例如,对于输入数字9,000,000,000,000,000,000
(在long
类型值范围内),下一个阶乘数是51,090,942,171,709,440,000
( 21!
的值),它在long
类型值范围之外。
您可以使用具有“无限”可能值范围的java.math.BigInteger
类,并对BigInteger
对象进行数学运算。
fact
应该声明为long
。 检查下面的代码:
public class TestJava {
public static void main(String[] args) {
try{
System.out.println("Input number: ");
Scanner scanner = new Scanner (System.in);
long number = scanner.nextLong();
if(number >= 2432902008176640000L) {
// log an appropriate message like can not handle
// long value greater than 2432902008176640000L
return 21;
}
long fact = 1;
int count =1;
while (fact <= number) {
count ++;
fact *=count;
}
System.out.println("output: "+ count);
}catch(Exception e){
e.printStackTrace();
}
}
}
更新(警告):
正如@Pshemo 提到的, if condition
,上面的代码在 20 之前都可以!但之后会导致无限循环问题。 因此,必须注意这种情况。 代码已相应更新。
您需要将fact
类型更改为 long
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.