繁体   English   中英

while 和 do-while 循环 最小值

[英]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,6482,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,8089,223,372,036,854,775,807之间。 当输入数字那么大时,您将找不到大于输入的正确fact值,因为您受到long类型值范围的限制。 例如,对于输入数字9,000,000,000,000,000,000 (在long类型值范围内),下一个阶乘数是51,090,942,171,709,440,00021!的值),它在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM