본문 바로가기

Programming Language/JAVA

반올림 Math.round(), 나머지 연산자

Math.round()

 

실수를 소수점 첫 째자리에서 반올림한 정수를 반환

 

long result = Math.round(4.52); // result = 5

// 소수점 특정 자리에서 반올림 하고 싶을 때 

class Ex3_11 {
	public static void main(String args[]) {
		
        double pi = 3.141592; // 소수점 3번째자리에서 반올림 하여 3.142의 결과를 얻고 싶을때   
        
		double shortPi = Math.round(pi * 1000) / 1000.0; 
        
        // 10^n 곱한 다음 다시 나누는 과정
        
        // Math.round(3.141592 * 1000) / 1000.0
        // Math.round(3141.592) / 1000.0 -> round로 3142 반올림
        // 3142 / 1000.0 
        // 3.142
        
        // 만약 3142 / 1000.0 이 아닌 1000을 했다면?
        
        // 3142(int)  /  1000(int) = 3 -> 예상과는 다른 결과
        
        // 3142 / 1000.0
        
        // 3142(int) / 1000.0 (double) -> 작은 값이 큰 값으로 형변환
        // 3142.0 / 1000.0 -> 3.142
        System.out.println(shortPi); // 3.142
     }
}

 

 


 

나머지 연산자 %

 

오른쪽 피연산자로 나누고 남은 나머지를 반환

 

class Ex3_11 {
	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입니다. 
       
       System.out.println(10 % 8); // 2
       System.out.println(10 % -8);  // 부호를 무시한다. 위와 같은 결과를 만든다.
     }
}

 


 

 

[ 자바의 정석 - 기초 유튜브 강의 영상 참고 ]

https://www.youtube.com/watch?v=hnzwWNG_bdA&list=PLW2UjW795-f6xWA2_MUhEVgPauhGl3xIp&index=28