【问题标题】:Variable is changed when I add "\n" in println [duplicate]当我在 println 中添加“\n”时,变量发生了变化 [重复]
【发布时间】:2021-09-02 14:29:35
【问题描述】:
我是一名新的 Java 学生,正在努力理解以下代码输出 11.7 而不是 1.7 会发生什么错误。为什么我使用char版本时代码会发生变化,为什么专门加了一个1?
public class FloatVersusDouble {
public static void main(String[] args) {
// FLOAT VS DOUBLE
float num =1.7f;
System.out.println(num + '\n');
}
}
谢谢
【问题讨论】:
标签:
java
floating-point
char
【解决方案1】:
当我在 println 中添加“\n”时变量发生了变化
您添加的不是"\n",而是'\n'。前者是String,后者是char。
+ 的含义取决于types of the operands:
- 当您将
+ 与float 和String 一起使用时,您正在执行字符串连接,因为至少有一个操作数是String;
- 当您将
+ 与float 和char 一起使用时,您正在执行数字加法,因为这两个操作数都具有数字类型。
对于数字加法,两个操作数经过binary numeric promotion,以使它们兼容加法。由于两个操作数中“最宽的”是float,因此char 被提升为float。由于\n 的代码点值为10,因此浮点值为10.f。然后,将两个浮点数相加,得到11.7f,打印为11.7。
如果您想打印num 后跟一个换行符(后跟另一个换行符,因为您使用的是System.out.println),请将'\n' 更改为"\n"。
【解决方案2】:
在 java 中,原始类型 char 在与数字运算符组合时被视为数字。
你在用代码做什么
num + '\n'
相当于伪代码
num + valueAsIntegerOf('\n')
而\n是ascii值10,所以你在做
num + 10
如果您想打印数字和两个新行(通过 println 方法添加一个,您可以通过不同的方式进行:
// First solution add a second println
System.out.println(num);
System.out.println();
// Second solution convert num to a string and add \n to that string
System.out.println(String.valueOf(num) + '\n');
// Same as the second solution but using the automatic conversion to
// string caused by "\n"
System.out.println(num + "\n");
最简单的方法是使用第三种解决方案。这项工作是因为您试图与运算符 + 数字和字符串结合使用。在这种情况下,数字将更改为字符串,并与 \n