2

请注意下面代码段中的打印语句。我的问题是,如果我尝试在 print 语句中添加两个双精度值,它会打印不正确,但是如果我将它们添加到 print 语句之外并将结果存储在变量中,我就无法正确打印它。

为什么这会起作用并打印出正确的结果?

public static void main(String argsp[]){
        Scanner input = new Scanner(System.in);

        double first, second, answer;

        System.out.println("Enter the first number: ");
        first = input.nextDouble();

        System.out.println("Enter the second number: ");
        second = input.nextDouble();

        answer = first + second;

        System.out.println("the answer is " + answer);

    }

为什么这会打印出错误的结果?

public static void main(String argsp[]){
        Scanner input = new Scanner(System.in);

        double first, second;

        System.out.println("Enter the first number: ");
        first = input.nextDouble();

        System.out.println("Enter the second number: ");
        second = input.nextDouble();

        System.out.println("the answer is " + first+second);

    }
4

3 回答 3

5

这是因为您在第二部分中所做的基本上是:

System.out.println("the answer is " + String.valueOf(first) + String.valueOf(second));

这就是编译器解释它的方式。因为+给方法赋值时的运算符String不是计算而是串联

如果您想在一行中完成,请这样做:

System.out.println("the answer is " + (first + second)); //Note the () around the calculation.
于 2012-05-24T13:14:45.943 回答
3

如果对运算符的优先级有疑问,请使用括号。读起来也更清楚。

System.out.println("the answer is " + (first+second));
于 2012-05-24T13:14:38.547 回答
2

在第二种情况下,双精度数被转换为Strings 因为+被认为是String串联。要解决此问题,请使用括号对应该执行数值计算的表达式进行分组:

 System.out.println("the answer is " + (first + second));
于 2012-05-24T13:15:39.903 回答