Study/JAVA

Math 클래스를 사용하여 신체 지수 구하기

AC 2019. 2. 23. 23:34

1
2
3
4
5
6
7
8
9
10
11
12
13
public class BioCalendar2 {
 
    public static final int PHYSICAL = 23; //상수 (개발자 정의)
    
    public static void main(String[] args) {
        int index = PHYSICAL;  // 상수값을 변수에 대입
        int days = 1200;
        
        double phyval = 100*Math.sin((days % index) * 2 * Math.PI/index);
        System.out.printf("나의 신체 지수 %1$.2f입니다.\n", phyval);
    }
}
 


Math 클래스는 java.util 패키지에 있고, 이 클래스의 메서드는 대부분 static으로 객체 생성 없이 Math.메서드() 형식으로 사용한다. 

대표적인 상수로 Math.PI(파이, 3.14), Math.E(지연지수, 2.718)가 있다.

라디안을 각도로 변경하는 toDegress(), 0과 1사이의 임의의 실수(0포함, 1미포함)를 만드는 random()도 Math 클래스에 속한다.

삼각함수 sin(), 각도 변환 toDegress(), 0과 1사이 임의의 값 random() 외에도 많은 수학함수가 있다.
필요에 따라 사용하면 된다.

sin(4x2xπ/23)은 sin(1.092)로 0.8878이다.

100x0.8879는 88.79로 신체 지수가 된다.



결과 : 나의 신체 지수 88.79입니다.





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class BioCalendar2 {
 
    public static final int PHYSICAL = 23; //상수 (개발자 정의)
    
    int index = PHYSICAL;  // 상수값을 변수에 대입
    static int days = 1200;
    
    public static void main(String[] args) {
        double phyval = getBioRhythm(days, PHYSICAL, 100);
        System.out.printf("나의 신체 지수 %1$.2f입니다.\n", phyval);
    }
    
    
    public static double getBioRhythm(long days, int index, int max) {
        return max*Math.sin((days % index) * 2 * Math.PI/index);
    }
}
 



static 메서드는 메서드에 static 예약어가 붙은 메서드로, 객체 생성 없이 호출할 수 있다. 


"public static 반환 타입 메서드이름(아규먼트){}" 형태로 사용한다.


사용자 정의 static 메서드를 선언한다. 반환 타입은 double, 메서드 이름은 getBioRhythm, 아규먼트(인자)는 long 타입 days, int 타입 index, int 타입 max 이다.


신체 지수를 계산하여 반환한다.


getBioRhythm() 메서드를 호출한다. -100 ~ 100 사이의 신체 지수 값을 구한다.



결과 : 위 예제와 동일


LIST