int i, j, k;
double a, b, c;
下列叙述顺序是正确的:
i = 3;
a = i + 5;
b = 12 / a;
c = i + b;
c = c - b;
j = 12 / 3;
a = 12 / 3;
b = 13 / 3;
// a gets the value 8.0
// b gets the value 1.5
// c gets the value 4.5
// c now gets the value 3.0
// j gets the value 4;
// a gets the value 4.0
// b gets the value 4.0!
在最后一行中,为什么 b 的值为 4.0? Java 中的 13/3 是 4 不是吗?为什么 4 会转换为 double ?这就是变量类型对值的作用吗?我认为 double 可以保存整数?
最佳答案
你这里的东西叫做 assignment conversion .
Assignment conversion occurs when the value of an expression is assigned to a variable: the type of the expression must be converted to the type of the variable.
Assignment contexts allow the use of one of the following:
an identity conversion
a widening primitive conversion
a widening reference conversion
a boxing conversion optionally followed by a widening reference conversion
an unboxing conversion optionally followed by a widening primitive conversion.
在这种情况下,您的赋值需要将表达式的值转换为 double
,因为这是赋值目标的类型。所需的转换为 widening primitive conversion ,它将表达式的值更改为具有包含该值的更广泛范围的类型。
从 int
转换为 double
时,不会丢失精度(double
可以保存 类型的所有值int
包括其所有数字,而 float
则不能)。但这并不意味着该值仍然是 int
。它已转换为表示相同值的 double
。
X
类型的变量永远不能保存除 X
之外的任何类型的值(多态除外,但这不适用于像 这样的基本类型int
和 double
)。
关于Java 变量赋值给 double。为什么该值会转换为 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34484450/