너와 나의 개발 고리

[JAVA/자바] Math클래스(abs 절대값, ceil 올림값, floor 버림값, max 최대값, min 최소값, random 랜덤값, round 반올림값) 본문

JAVA

[JAVA/자바] Math클래스(abs 절대값, ceil 올림값, floor 버림값, max 최대값, min 최소값, random 랜덤값, round 반올림값)

Oli-Viaaaa 2023. 6. 18. 17:20

Java의 Math 클래스는 수학 계산에 사용할 수 있는 메소드를 제공하며,

Math 클래스가 제공하는 메소드는 모두 정적이므로 Math 클래스로 바로 사용이 가능하다.

 

주요 메소드는 아래와 같다

구분 코드 리턴값
절대값    int v1 = Math.abs(-5);
   double v2 = Math.abs(-3.14);
   v1 = 5
   v2 = 3.14
올림값    double v3 = Math.ceil(5.3);
   double v4 = Math.ceil(-5.3);
   v3 = 6.0
   v4 = -5.0
버림값    double v5 = Math.floor(5.3);
   double v6 = Math.floor(-5.3);
   v5 = 5.0
   v6 = -6.0
최대값    int v7 = Math.max(5,  9);
   double v8 = Math.max(5.3,  2.5);
   v7 = 9
   v8 = 5.3
최소값    int v9 = Math.min(5,  9);
   double v10 = Math.min(5.3,   2.5);
   v9 = 5
   v10 = 2.5
랜덤값    double v11 = Math.random();    0.0 <= v11 <1.0
반올림값    long v14 = Math.round(5.3);
   long v15 = Math.round(5.7);
   v14 = 5
   v15 = 6

 

Math 메소드를 활용한 예시는 아래의 코드를 통해 확인 가능하다.

 

 

 

double random = Math.random();

random() 메소드는 0.0과 1.0 사이의 double 타입 난수를 리턴한다.

 

특정 범위의 난수를 생성하려면 Math.random()의 반환값을 조정해야 한다.

int min = 1;
int max = 10;
int range = max - min + 1;
int random = (int) (Math.random() * range) + min;

위의 코드는 Math.random()의 반환값에 범위를 곱한 후 최소값을 더하여 난수를 생성한다.

(int)로 형변환을 수행하여 정수형으로 변환하여 1 이상 10 이하의 정수 난수를 생성할 수 있다.

 

 

여러개의 난수를 생성하는 방법은 반복문을 사용하여 Math.random()을 호출할 수 있다.

for (int i = 0; i < 5; i++) {
    double random = Math.random();
    System.out.println(random);
}

위의 코드는 0이상 1미만의 범위에서 5개의 난수를 생성하고 그 값을 출력한다.