3

我在使用 java += 运算符时遇到了一些意外。

显然,这编译:

int a = 0;
a += 3/2.0;
System.out.println(a);  // outputs "1"

虽然,这不

int a = 0;
a = a + (3/2.0);   // eclipse compiler error "Type mismatch: cannot convert from double to int"
System.out.println(a);

这是预期的行为吗?我觉得奇怪的是 += 运算符没有报告“类型不匹配”,因为它是一个“添加和分配”运算符,您在其中添加一个双精度数,它给出双精度结果,然后分配给一个 int 变量。相反,它会默默地转换(并截断)结果。

4

3 回答 3

3

这就是 += 从C. 这是“功能”而不是错误

请参阅Java 的 +=、-=、*=、/= 复合赋值运算符

顺便说一句,你可以试试这个

char ch = '0';
ch *= 1.1; // ch = '4'

另请参阅我的帖子http://vanillajava.blogspot.com/2012/11/java-and-implicit-casting.html

于 2013-06-11T09:47:59.473 回答
2

int a = a + (3/2.0); 不编译,因为:

  • int+double导致double
  • a被称为int
  • double转换为 int 丢失

int a += 3/2.0; 编译自:

  • int+double导致双倍
  • a被称为int
  • double是可转换的int,幸运的是,编译器添加了一个类似于以下的隐式转换:

    int a = (int)(a+ 3/2.0);. 这是由于op=编译器比基本赋值运算符更巧妙地解释了特殊符号:=

于 2013-06-11T09:49:52.137 回答
0

这不是错误,它发生了隐式转换。

例如。

Byte b=3;

b+=5;  //compiles

b=b+5; //doesnt compiles

这里发生的是

a=a+3/2.0;   // 3/2.0 produces double , it add int to double but cant convert it implicitly to int.

a += 3/2.0;  // here implicit conversion after addition of a to 3/2.0 happends from double to int
于 2013-06-11T09:48:59.717 回答