Ch3-11~12. Math.round()
0. 목차
Chapter3. 연산자
Ch3 - 11. Math.round()로 반올림하기
Ch3 - 12. 나머지 연산자 %
Ch3 - 11. Math.round()로 반올림하기
▶ Math.round()란?
▷ 실수를 소수점 첫째 자리에서 반올림한 정수를 반환
long result = Math.round(4.52);
System.out.println(result);
// console
5
▶ 실습
▷ double pi = 3.141592;
pi
에서 소수점 셋째 자리까지 반올림 하여 3.142
를 출력하시오
Math.round()
사용
double pi = 3.141592;
double thirdUpPi = Math.round(pi * 1000) / 1000.0;
System.out.println(thirdUpPi);
// console
3.142
- 계산과정
Math.round(pi * 1000) / 1000.0
→ Math.round(3.141592 * 1000) / 1000.0
→ Math.round(3141.592) / 1000.0 // 소수점 첫째자리 5에서 반올림 → 3142
→ 3142 / 1000.0(double) // int ÷ double = double
→ 3.142(double)
▷ double pi = 3.141592;
pi
를 3.141
로 출력하시오
double pi = 3.141592;
double thirdUpPi = ((int)(pi * 1000) / 1000.0);
// console
3.141
- 계산과정
((int)(pi * 1000) / 1000.0)
// (pi * 1000)을 괄호를 사용하여 우선순위
→ Math.round(3.141592 * 1000) / 1000.0
→ Math.round(3141.592) / 1000.0 // 소수점 첫째자리 5에서 반올림 → 3142
→ 3142 / 1000.0(double) // int ÷ double = double
→ 3.142(double)
Ch3 - 12. 나머지 연산자 %
▶ 나머지 연산자 %란?
▷ 오른쪽 피연산자로 나누고 남은 나머지를 반환
10 ÷ 8 = 1…2 // 몫 = 1, 나머지 = 2
10/8 = 1 // 몫
10%8 = 2 // 나머지
System.out.println(10/8);
System.out.println(10%8);
// console
1 // 몫
2 // 나머지
▶ % : 부호는 무시
▷ 10%8 = 10%-8
System.out.println(10%8);
System.out.println(10%-8);
// console
2
2