3-11 반올림 - Math.round()
실수를 소수점 첫 째자리에서 반올림한 정수를 반환

int / double은 double / double로 바뀐다.
import java.util.Scanner;
public class lnterfaceEx {
public static void main(String[] args) {
double pi = 3.141592;
System.out.println(pi); //3.142를 얻으려면
System.out.println(pi*1000);
System.out.println(Math.round(pi*1000));
System.out.println(Math.round(pi*1000)/1000);
System.out.println(Math.round(pi*1000)/1000.0);
}
}
결과값
pi = 3.141592
pi*1000 = 3141.592
Math.round(pi*1000) = 3142
Math.round(pi*1000)/1000 = 3
Math.round(pi*1000)/1000.0 = 3.142
소수점 아랫값을 자를때 형변환을 사용하면 된다.
import java.util.Scanner;
public class lnterfaceEx {
public static void main(String[] args) {
double pi = 3.141592;
System.out.println(pi); //3.141을 얻으려면
System.out.println(pi*1000);
System.out.println((int)(pi*1000)/1000);
System.out.println((int)(pi*1000)/1000.0);
}
}
결과값
pi = 3.141592
pi*1000 = 3141.592
(int)(pi*1000)/1000 = 3
(int)(pi*1000)/1000.0 = 3.141
3-12 나머지 연산자 %
오른쪽 피연산자로 나누고 남은 나머지를 반환
나누는 피연산자는 0이 아닌 정수만 가능(부호는 무시)

import java.util.Scanner;
public class lnterfaceEx {
public static void main(String[] args) {
int x = 10;
int y = 8;
System.out.printf("%d을 %d로 나누면, %n", x, y);
System.out.printf("몫은 %d이고, 나머지는 %d입니다.%n", x / y, x % y);
}
}
결과값
10을 8로 나누면,
몫은 1이고, 나머지는 2입니다.
'프로그래밍 언어 > 자바의 정석 기초편' 카테고리의 다른 글
자바의 정석 기초편 ch3-15,16 논리 연산자, 논리 부정 연산자 (0) | 2022.05.12 |
---|---|
자바의 정석 기초편 ch3-13,14 비교 연산자, 문자열의 비교 (0) | 2022.05.12 |
자바의 정석 기초편 ch3-9,10 사칙 연산자, 산술변환 (0) | 2022.05.12 |
자바의 정석 기초편 ch3-7,8 형변환 연산자, 자동 형변환 (0) | 2022.05.11 |
자바의 정석 기초편 ch3-5,6 증감연산자, 부호연산자 (0) | 2022.05.10 |