본문 바로가기
자바(Java)/자바 AP

AP Computer Science A Java Quick Reference (3) Math Class

by 긱펀 2024. 3. 28.
반응형

AP Computer Science A Java Quick Reference 

(3) Math Class

 

 

 

자바에서 Math 클래스는 자바를 설치하면 포함되는 클래스로서, 이 클래스 안에 있는 메소드들은 static method이기 때문에 object를 만들지 않고 "클래스이름.메소드이름()" 방식으로 바로 사용가능합니다.

Static methods (also called class methods) are called using the class name and the dot operator (.) followed by the method name. You do not need to create an object of the class to use them. You can use ClassName.methodName() or just methodName() if they are called from within the same class.

 

 

아래는 자바의 Math Class에 있는 주요 메소드이고, 이는 APCSA subset에 포함된 메소드 이기도 합니다.

  • int abs(int) : Returns the absolute value of an int value (which is the value of a number without its sign, for example Math.abs(-4) = 4).
  • double abs(double) : Returns the absolute value of a double value.
  • double pow(double, double) : Returns the value of the first parameter raised to the power of the second parameter.(for example, pow(2,3) => 2 to the power of 3 which is 8
  • double sqrt(double) : Returns the positive square root of a double value.
  • double random() : Returns a double value greater than or equal to 0.0 and less than 1.0 (not including 1.0!).

 

[주의]
Math 클래스의 method는 리턴값에 주의해야 합니다.

Math.abs(value)는 value의 타입에 맞춰서 리턴타입이 정해집니다.
Math.abs(45);    // returns 45
Math.abs(-45);   // returns 45
Math.abs(33.3);  // returns 33.3
Math.abs(-33.3); // returns 33.3

Math.pow()는 리턴값이 double 타입입니다.
Math.pow(2 , 3); // returns 8.0
Math.pow(10, 6); // returns 1000000.0
Math.pow(2, -3); // returns 0.125​

Math.sqrt()는 리턴값이 double 타입입니다.
Math.sqrt(9); // returns 3.0​

 

 

[예제1]

아래의 Math 클래스의 method 코드를 실행해 보세요.

1
2
3
4
5
6
7
public class Main {
    public static void main(String[] args) {
        System.out.println( Math.abs(-2) );         // 2
        System.out.println( Math.sqrt(4) );         // 2.0
        System.out.println((int)Math.pow(23) );   // 8
    }
}
cs

 

  • 위 코드의 5번째 줄 처럼 리턴타입이 double인 것을 int로 형변환(casting)을 하면 정수로 나타낼 수 있습니다.

 

 

[유제1-1] 아래 주석에 적힌 mission 부분을 코딩하여 (1)~(3)의 결과값이 출력되게 해보세요.

1
2
3
4
5
6
7
8
9
public class Main {
    public static void main(String[] args) {
        // coding mission (1)~(3) below;
        // (1) absolute value of -4,
        // (2) square root of 9,
        // (3) 3 raised to the power of 2.
        
    }
}
cs

 

 

[유제1-2] 아래의 sqrt 메소드 코드 중 사용법이 맞는것은?

1
2
3
4
5
6
1. Math.sqrt(2)
2. Math.sqrt()
3. Math.sqrt(24)
4. Math.sqrt(2 + 3)
5. Math.sqrt 2
6. Math.sqrt(Math.sqrt(2))
cs

 

A. 1
B. 1,3,6
C. 2, 5
D. 3, 4
E. 1,4,6

 

 

[유제 1-3]

The distance between two numbers on the number line is defined as the absolute value of their difference. Their difference is just what you get when you subtract one from the other. For example, the distance from 0 to 3 is 3, the distance from -3 to 0 is 3, and the distance from -3 to 1 is 4.

 

Which of the following are correct expressions to compute the distance between the numbers a and b.

 

A. Math.abs(a) - Math.abs(b)

B. Math.abs(a - b)

C. Math.abs(a + b)

 

[유제1-4]

The distance between two numbers on a number line, as we discussed in the problem above, is defined as the absolute value of their difference. Their difference is just what you get when you subtract one from the other. For example, the distance from 0 to 3 is 3, the distance from -3 to 0 is 3, and the distance from -3 to 1 is 4.


Fill in the method distance below so it correctly computes the distance between two numbers a and b using subtraction and Math.abs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class DistanceCalculator
{
    public static double distance(double a, double b)
    {
        double distance = 0.0;
        // TODO: calculate the distance from a to b using subtraction and Math.abs.   
    }
 
    public static void main(String[] argv)
    {
        System.out.println("distance(13.5, 26.2) = " + distance(13.526.2));
        System.out.println("distance(26.2, 13.5) = " + distance(26.213.5));
        System.out.println(distance(13.526.2== distance(13.526.2));
    }
}
 
cs

 

 

 

 

[예제2] 

아래의 random() 메소드 코드를 실행해 보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Main {
    public static void main(String[] args) {
        System.out.println(Math.random()); // 0.0 =< x < 1
        // 0.00000... ~ 0.99999
        
        int rnd1 = (int) (Math.random() * 10);
        System.out.println(random_int); // 0 =< x <= 9
        System.out.println(random_int + 1); // 1 =< x <= 10
        
        // rnd2 is in the range 5-10 (including 10).
        // The range is 10-5+1 = 6.
        int rnd2 = (int)(Math.random()*6+ 5;
 
        // rnd3 is in the range -10 up to 9 (including 9). 
        // The range is doubled (9 - -10 + 1 = 20) and the minimum is -10.
        int rnd3 = (int)(Math.random()*20- 10;
    }
}
cs

 

  • Math.random() 메소드는 0(포함) ~ 1(미포함) 사이의 무작위 값을 double 타입으로 리턴해준다.
  • Math.random() returns a random number between 0.0-0.99.
  • (int)(Math.random()*range) + min moves the random number into a range starting from a minimum number.

 

[참고]
random 값이 double 타입으로 리턴될 때 이 double값을 ==로 비교하면 안된다. ==는 int값 비교할 때 사용하는것이고 double은 Double.compare(num1, num2)로 비교한다.아래의 예시코드를 보자.
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Main {
    public static void main(String[] args) {
        double a = 1.14;
        double b = 2.14;
        
        int r = Double.compare(a,b);
        // a == b return 0
        // a > b return 1
        // a < b return -1
        System.out.println(r);
        
    }
}
cs

 

 

[유제2-1]

Which of the following would return a random number from 1 to 5 inclusive?

 

A. ((int) (Math.random() * 5))
B. ((int) (Math.random() * 6))
C. ((int) (Math.random() * 5) + 1)

 

 

[유제2-2]

Which of the following would return a random number from 0 to 10 inclusive?

 

A. ((int) (Math.random() * 10))
B. ((int) (Math.random() * 11))
C. ((int) (Math.random() * 10) + 1)

 

 

[유제2-3] APCSA sample question

Which of the following statements assigns a random integer between 25 and 60, inclusive, to rn?

 

A. int rn = (int) (Math.random() * 25) + 36;
B. int rn = (int) (Math.random() * 35) + 25;
C. int rn = (int) (Math.random() * 26) + 60;
D. int rn = (int) (Math.random() * 36) + 25;
E. int rn = (int) (Math.random() * 60) + 25;

 


 

[유제 정답은 아래 "더보기" 클릭]

더보기

[유제1-1 정답]

1
2
3
4
5
6
7
8
9
10
11
12
public class Main {
    public static void main(String[] args) {
        // coding mission (1)~(3) below;
        // (1) absolute value of -4,
        System.out.println(Math.abs(-4));
        // (2) square root of 9,
        System.out.println((int)Math.sqrt(9));
        // (3) 3 raised to the power of 2
        System.out.println((int)Math.pow(3,2));
        
    }
}
cs

 

[유제1-2 정답]

 E

(✅ This is a simple call to Math.sqrt with the argument 2.
✅ The argument passed to Math.sqrt is the value of the expression 2 + 3, namely 5.
✅ The argument passed to Math.sqrt is the value of another call to Math.sqrt which is perfectly fine.)

 

[유제1-3 정답]

B

(a - b gives us the difference and Math.abs gives us the absolute value of that difference.)

 

[유제1-4 정답]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class DistanceCalculator
{
    public static double distance(double a, double b)
    {
        // TODO: calculate the distance from a to b using subtraction and Math.abs.
        double distance = 0.0;
        distance = Math.abs(a - b);
        return distance;
    }
 
    public static void main(String[] argv)
    {
        System.out.println("distance(13.5, 26.2) = " + distance(13.526.2));
        System.out.println("distance(26.2, 13.5) = " + distance(26.213.5));
        System.out.println(distance(13.526.2== distance(13.526.2));
    }
}
 
cs

 

[유제2-1 정답]

C

(The first part would return a number between 0 and 4 and when you add 1 you get a number from 1 to 5 inclusive.)

 

[유제2-2 정답]

B

 

[유제2-3 정답]

D

(Yes, (int)(Math.random()*36) + 25 moves the random number into a range of 36 numbers starting from a minimum number 25 up to 60. The range is (max number - min number + 1) which is (60-25 +1) = 36.)

 


 

728x90
반응형

댓글