请注意下面代码段中的打印语句。我的问题是,如果我尝试在 print 语句中添加两个 double ,它会打印错误,但如果我将它们添加到 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);
}
最佳答案
这是因为你在第二部分基本上做的是:
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.
关于java - 基本的java打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10738148/