基本java打印
请注意下面代码段中的打印语句。我的问题是,如果我尝试在print语句中添加两个double,它会错误地打印,但是如果我在print语句之外添加它们,并将结果存储在变量中,那么我就无法正确打印它 为什么这样做并打印出正确的结果基本java打印,java,Java,请注意下面代码段中的打印语句。我的问题是,如果我尝试在print语句中添加两个double,它会错误地打印,但是如果我在print语句之外添加它们,并将结果存储在变量中,那么我就无法正确打印它 为什么这样做并打印出正确的结果 public static void main(String argsp[]){ Scanner input = new Scanner(System.in); double first, second, answer;
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);
}
如果对运算符的优先级有疑问,请使用parens。阅读起来也更清晰
System.out.println("the answer is " + (first+second));
这是因为你在第二部分基本上做的是:
System.out.println("the answer is " + String.valueOf(first) + String.valueOf(second));
编译器就是这样解释的。因为将+
字符串提供给方法时的+
运算符不是计算,而是串联
如果要在一行中完成,请按以下方式进行:
System.out.println("the answer is " + (first + second)); //Note the () around the calculation.
在第二种情况下,double被转换为
String
s,因为+
被认为是String
串联。要解决此问题,请使用括号将应执行数值计算的表达式分组:
System.out.println("the answer is " + (first + second));
结果如何?对我来说很好。输入第一个数字:2输入第一个数字:2答案是2.02。0@owengerigOP正在尝试通过邻近性生成编译器组操作数。看到那两个人是如何拥抱在一起的吗?:)