2013-06-17 15 views
5

Właśnie utworzyłem prosty program java, używając typu danych short.
Program wygląda następująco:nieoczekiwane zachowanie w typach

class test 
{ 
    public static void main(String arg[]) 
    { 
     short x=1; 
     short x_square=x*x; 
    } 
} 

Ten program zgłasza błąd:

java:6: possible loss of precision 
found : int 
required: short 

Jak kompilator zakłada int? Nie ma zmiennej int w tym programie wszystkie zmienne są zadeklarowane jako short.

Odpowiedz

11

Podczas operacji arytmetycznej typy całkowite są zawsze traktowane jako prymitywy int w Javie, jeśli żadna z nich nie jest typu long. Małe typy liczb całkowitych są promowane do int, a wynikiem operacji jest int. Stąd x*x jest typu rzucanego jako int i próbujesz przypisać go do short. Aby zawęzić konwersję, potrzebujesz wyraźnej obsady do short.

short x_square=(short)(x*x); 

Wykonaj JLS 4.2.2

If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).

Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

+0

dzięki za link, który mi pomógł –

4

Od the specification:

If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).

Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

Dodanie krótkiego i krótkiego sprawia int. Jeśli chcesz zapisać wynik w zmiennej typu int, musisz go rzucić.

+0

dzięki za informacje –

2

Spróbuj przesłać go: short x_square=(short)(x*x)

+0

dzięki za informacje –

4

Ponieważ mnożenie dwóch szorty zwraca int w Javie. Aby pozbyć się tego błędu trzeba mieć wyraźny typ rzucania:

short x_square=(short)x*x; 

Lub, można również wykonać następujące czynności:

short x_square = x; 
x_square *= x_square; 
+0

dzięki za informacje –

Powiązane problemy