Java 变量赋值给 double。为什么该值会转换为 double ?

标签 java

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 之外的任何类型的值(多态除外,但这不适用于像 这样的基本类型intdouble)。

关于Java 变量赋值给 double。为什么该值会转换为 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34484450/

相关文章:

java - Elasticsearch:在 java.lang.OutOfMemoryError:Java 堆空间后重新启动节点

java - 使 java 类仅在项目/应用程序工作区内可见

java - 防止 swagger 将类似的正则表达式映射合并到单个操作

java - 后增量运算符和前增量运算符之间的性能差异?

java - 如何使用java更改png文件的对比度

java - Java 泛型参数之间的区别

java - 如何删除tomcat jsp中的 session ?

java - 我是否必须将 java 中已经通用的数组转换为通用类型

java - 为什么 Java 的 JIT 编译器不将所有内容都翻译成本地代码?

java - 使用 MPJ express 寄送元素