为什么很大的双输入会返回“ Infinity”而不是Java中的错误?

时间:2018-07-17 09:34:19

标签: java double

初始化值大于1E309的double变量会在编译期间出错。 但是,将该值作为输入不会产生任何错误。实际上,打印double变量得到String "Infinity"。 为什么会这样?

import java.util.Scanner;

public class BigDouble {

    public static void main(String[] args) {
        double number;

        Scanner keyboard = new Scanner(System.in);

        System.out.print("Enter a number:  ");
        number = keyboard.nextDouble();

        System.out.println(number);

    }
}

2 个答案:

答案 0 :(得分:0)

您没有得到任何错误,因为Choices commands = new Choices(); GrammarBuilder gBuilder = new GrammarBuilder(); public void Masokey_Load(object sender, EventArgs e) { // Choices commands = new Choices(); commands.Add(new string[] { Atext.Text, Dtext.Text}); // GrammarBuilder gBuilder = new GrammarBuilder(); gBuilder.Append(commands); Grammar grammar = new Grammar(gBuilder); recEngine.LoadGrammarAsync(grammar); recEngine.SetInputToDefaultAudioDevice(); recEngine.SpeechRecognized += RecEngine_SpeechRecognized; } //save_btn public void Savebtn_Click(object sender, EventArgs e) { commands.Add(new string[] { Atext.Text, Dtext.Text}); gBuilder.Append(commands); } public void RecEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { if(e.Result.Text == Atext.Text) { PressKey(0x1E); } else if (e.Result.Text == Dtext.Text) { PressKey(0x20); } } 解析了nextDouble(),而不是Doubledouble作为包装类,具有几个有用的常量:

Double

在内部,public static final double POSITIVE_INFINITY = 1.0 / 0.0; public static final double NEGATIVE_INFINITY = -1.0 / 0.0; public static final double NaN = 0.0d / 0.0; 使用nextDouble()提供结果,而不管输入的数字在什么范围内。

Double.parseDouble(String)

如果该数字不在public double nextDouble() { ... try { return Double.parseDouble(processFloatToken(next(floatPattern()))); } catch (NumberFormatException nfe) { ... } } 范围内,则会为您提供doublePOSITIVE_INFINITY

NEGATIVE_INFINITY

答案 1 :(得分:0)

当您说“初始化一个值大于1E309的双精度变量”时,您可能会说:

double number = 1E6000;

在此,按原样显示的“ 1E6000”称为“文字”值。您正在编写程序,并要求它按字面意义将此值用作double。

这是不可能的,因为此值太大。因此,让您这样做是没有意义的。相反,请使用可以实际表示的值,或者如果要使用无穷大,请使用常量Double.POSITIVE_INFINITY。拒绝原义的1E6000不会使您失去任何选择。

但是,当您不处理字面值而是一些计算的结果时,则浮点数的常见约定是,如果计算的值太大而无法表示,则可以提供无穷大代表它。不是错误。

程序员在这里无法预测用户输入的数字太大而无法准确表示。没有什么比将结果计算出的值表示为无穷大更好的建议了。