Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

3.4 정확한 계산은 정수 연산으로 본문

이것이 자바다/03 연산자

3.4 정확한 계산은 정수 연산으로

빌드이너프 2024. 3. 29. 10:21
package ch03.sec04;

public class AccuracyExample1 {
	public static void main(String[] args) {
		int apple = 1;
		double pieceUnit = 0.1;
		int number = 7;
		
		double result = apple - number*pieceUnit;
		System.out.println(result);
	}
}
0.29999999999999993

result의 값이 정확히 0.3이 되지 않는다

-> 부동 소수점 방식을 사용하는 실수 타입에서 흔히 일어난다

 

정확한 계산이 필요하다면 정수 연산으로 변경해서 사용하는 것이 좋다

package ch03.sec04;

public class AccuracyExample2 {
	public static void main(String[] args) {
		int apple = 1;
		int totalPieces = apple * 10;
		int number = 7;
		
		int result = totalPieces - number;
		System.out.println(result);
		System.out.println(result / 10.0);
	}
}
3
0.3