2

下面的代码给出了以下错误:

错误:C:\Users\Laptop\algs4\hello\Main.java:8: 可能丢失精度

发现:int

要求:短

import java.util.* ; 
import java.math.* ; 
import java.io.* ; 
public class Main{
    public static void main(String[] args){
        short[][] arr = new short[1][2]; 
        short val = 9 ; 
        arr[0][0] = arr[0][0] + val ; 
    }
}

但以下没有错误。

import java.util.* ; 
import java.math.* ; 
import java.io.* ; 
public class Main{
    public static void main(String[] args){
        short[][] arr = new short[1][2]; 
        short val = 9 ; 
        arr[0][0] += val ; 
    }
}

这可能是什么原因?

4

3 回答 3

3

try arr[0][0] = (short)(arr[0][0] + val);

with

arr[0][0] += val ;

the compiler makes the casting for you

于 2013-01-05T16:32:11.413 回答
3

In the following:

    arr[0][0] = arr[0][0] + val ; 

both arguments are first promoted to int, the addition is carried out, and the result is implicitly narrowed to short. This could cause loss of precision, hence the error.

The second version:

    arr[0][0] += val ; 

is defined by the Java Language Specification to be equivalent to

    arr[0][0] = (short)((int)arr[0][0] + (int)val); 

In other words, this behaves as if there was an explicit cast, hence no error.

You can achieve the same effect in the first version by adding an explicit cast:

arr[0][0] = (short)(arr[0][0] + val); 
于 2013-01-05T16:33:13.060 回答
1
import java.util.* ; 
import java.math.* ; 
import java.io.* ; 
public class timous{
    public static void main(String[] args){
        short[][] arr = new short[1][2]; 
        short val = 9 ; 
        arr[0][0] = (short)(arr[0][0] + val) ; 
    }
}

This code is not giving any errors. :)

于 2013-01-05T16:35:10.980 回答