본문 바로가기
프로그래밍 언어/자바의 정석 기초편

자바의 정석 기초편 ch3-11,12 반올림 Math.round(), 나머지 연산자

by life grow 2022. 5. 12.

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);
	}	
}
결과값
108로 나누면, 
몫은 1이고, 나머지는 2입니다.