Language/Java

연산자와 타입의 범위

leegeonwoo 2023. 8. 6. 14:39

아래의 연산코드중에서 잘못된 부분을 고치려면

public class Main {

public static void main(String[] args) {

byte a = 10;

byte b = 20;

byte c = a + b;

 

char ch = 'A';

ch = ch + 2;

 

float f = 3 / 2;

long l = 3000 * 3000 * 3000;

 

float f2 = 0.1f;

double d = 0.1;

 

boolean result = d == f2;

 

System.out.println("c=" + c);

System.out.println("ch=" + ch);

System.out.println("f="+f);

System.out.println("l=" + l);

System.out.println("result=" + result);

}

}

 

1. byte c = a + b를 연산하면 a+b가 int타입으로 변환되기때문에 byte타입인 c에 저장할 수 없다.

그래서 (a+b)의 연산을 (byte)로 형변환 해주어야 한다.

 

2.비슷한 이유로 ch = ch + 2도 ch+2는 int타입의 정수값의 결과를 갖기때문에 char타입인 ch에는 저장할 수 없다.

그러므로 (ch+2)의 결과를 (char)로 형변환 해주어야한다.

 

3.float 3/2는 int타입과 int타입의 연산이므로 소수점자리는 버려지기때문에 정확한 값을 얻기 위해서는 피연산자에 f를 추가해주어야한다.

 

4.long l = 3000 * 3000 * 3000의 경우 피연산자들이 모두 int타입이므로 long l에 저장되기전에 이미 값이 손실된채로 변수l에 저장되기때문에 정확한값을 얻기위해서는 피연산자에 접미사L을 붙여주어야한다.

 

5.boolean result = d == f2는 false가 반환되는데 연산 시에 float를 double로 형변환할때 오차가 발생할 수 있다.

그래서 float값을 double로 형변환하기 보다는 float로 형변환해서 비교하는 것이 true의 결과를 얻을 수 있다.

 

public class Main {

public static void main(String[] args) {

byte a = 10;

byte b = 20;

byte c = (byte)(a + b);

 

char ch = 'A';

ch = (char)(ch + 2);

 

float f = 3f / 2;

long l = 3000L * 3000 * 3000;

 

float f2 = 0.1f;

double d = 0.1;

 

boolean result = (float)d == f2;

 

System.out.println("c=" + c);

System.out.println("ch=" + ch);

System.out.println("f="+f);

System.out.println("l=" + l);

System.out.println("result=" + result);

 

 

}

}

 

 

 

 

실행결과:

c=30

ch=C

f=1.5

l=27000000000

result=true

 

728x90