【问题标题】:Program crashes when given high values给定高值时程序崩溃
【发布时间】:2018-02-20 10:55:51
【问题描述】:

我的编码,我试图制作一个无论用户输入什么都不会崩溃的程序,该程序将划分并打印出答案。我已经搜索但找不到任何帮助! 该编码适用于小于 100000000 或 199999999 的数字,您明白了。

Scanner in = new Scanner(System.in);
double n1 = in.nextInt();
double n2 = in.nextInt();
double n3 = n1/n2;
System.out.println(n3);

【问题讨论】:

标签: java int double java.util.scanner system


【解决方案1】:

您正在使用in.nextInt(),它将读取一个值小于2^31 -1 的整数(当然它会转换为double)。但是当你给出的值超过(2^31) - 1 时,比如12589691475,nextInt() 无法读取它们,因为它们是非常大的数字。

请改用in.nextDouble()。

【讨论】:

  • 我不知道它对 OP 是否重要,但双除法的行为与整数除法不同。如果它适合long,那可能是第一个选择。
【解决方案2】:

使用

in.nextDouble();

或

in.nextLong();

【讨论】:

    【解决方案3】:

    对于任意大数字,请使用java.math.BigInteger 或java.math.BigDecimal。

    Scanner in = new Scanner(System.in);
    BigInteger n1 = new BigInteger(in.nextLine());
    BigInteger n2 = new BigInteger(in.nextLine());
    BigInteger n3 = n1.divide(n2);
    System.out.println(n3);
    

    【讨论】:

      猜你喜欢
      • 2012-08-07
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多