Math 클래스

coding by 스플릿·2021년 12월 15일

Java1

목록 보기
14/44

Math.round( 반올림할 값 ) : 소수점 첫째 자리에서 반올림해서 int로 반환

  • 소수점 첫째자리에서 반올림한 값을 구할 때
class Main {
    public static void main(String[] args) {
       double x = 3.141592;
       double y = Math.round(x);
       System.out.printf("x = %f,y = %f\n",x,y);
       //출력 : x = 3.141592,y = 3.000000
    }
}
  • 원하는 소수점 자리에서 반올림한 값을 구할 때
class Main {
    public static void main(String[] args) {
       double x = 3.141592;
       y = Math.round(x * 1000)/1000.0;
       System.out.printf("x = %f,y = %f",x,y);
       //출력 : x = 3.141592,y = 3.142000
    }
}

y = Math.round(x * 1000)/1000.0; 에서 1000.0으로 나누는 이유 ?

  • 1000으로 나눌시에는 두 피연산자가 모두 int라 값이 int로 나와서 3이 나온다.

Math.random()

0.0이상 1.0미만에 있는 double타입의 난수(임의의 수)을 반환

  • 기본사용
class Main {
    public static void main(String[] args) {
       double x = Math.random();
       System.out.println(x);
    }
}
  • 1에서 10사이의 정수 중의 난수를 구할 때

    1. Math.random()에 최대범위 - 1 을 곱해준다
      • 0.0 * 9 <= Math.random() * 9 < 1.0 * 9

    2. int로 형변환 한다
    • (int)0.0 <= (int)(Math.random() * 9) < (int)9.0

    1. 1을 더해준다
    • 0 + 1 <= (int)(Math.random() * 9 ) + 1 < 9 + 1

class Main {
    public static void main(String[] args) {
       int x = (int)(Math.random()*9) + 1;
       System.out.println(x);
    }
}

0개의 댓글