package ch09utility;
public class MathEx {
public static void main(String[] args) {
//Math math = new Math(); //기본 생성자가 없음.
double d1 = -12.3456;
double d2 = 34.56;
double result = Math.abs(d1);
System.out.println("절대값 : "+Math.abs(result));
System.out.println("올림 : "+Math.ceil(d2));
System.out.println("버림 : "+Math.floor(d2));
System.out.println("반올림 : "+Math.round(d2));
System.out.println("2의 2제곱 : "+Math.pow(2,2));
System.out.println("2의 3제곱 : "+Math.pow(2,3));
System.out.println("루트 4 : "+Math.sqrt(4));
System.out.println("큐빅 루트 64 : "+Math.cbrt(64));
int su01 =12, su02=15;
System.out.println("큰 수 : "+Math.max(su01, su02));
System.out.println("작은 수 : "+Math.min(su01, su02));
System.out.println("0이상 1미만의 랜덤 수 : "+Math.random()); // 0.0(포함) 이상 1.0(제외) 미만의 난수(double 타입)**를 생성
//두 변이 각각 4.0, 3.0인 직각 삼각형의 대변 길이를 구해 보세요.
double width = 4.0, height = 3.0;
double diagonal; //정답 5.0
diagonal = Math.sqrt(Math.pow(width,2.0)+Math.pow(height,2.0));
System.out.println("대각선의 길이" +diagonal);
//문제 01 : 모든 요소들의 절대 값을 각각 3제곱한 결과들의 총합을 정수로 출력하세요.
int[] arr = {3,-5,4};
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += (int)Math.abs(Math.pow(arr[i],3));
}
System.out.println(sum);
int total = 0; // 정답 216
//문제 02 : 배열 요소들의 문자열 길이의 제곱 값을 구한 다음 모든 값의 총합에 루트값은?
// 풀이 : 3*3+4*4+5*5+6*6=86
// 루트 86 = 9.273618495
// for, String의 length(), Math의 pow, sqrt
String[] myarr = {"son","hello","love","flower"};
double lengthString = 0;
result = 0;
for (int i = 0; i < myarr.length; i++) {
lengthString = myarr[i].length();
result += Math.pow(lengthString,2);
}
System.out.println(Math.sqrt(result));
}
}
- abs(int a) → int
설명: 절댓값을 반환합니다.
double, float, long 타입도 각각의 절댓값을 반환하는 오버로드된 메서드가 존재.
- ceil(double a) → double
설명: 소수점 이하를 올림하여 가장 가까운 정수를 반환합니다.
- floor(double a) → double
설명: 소수점 이하를 내림하여 가장 가까운 정수를 반환합니다.
- round()
- round(float a) → int,
- round(double a) → long
설명: 가장 가까운 정수로 반올림합니다.
- pow(double a, double b) → double
설명: a의 b 거듭제곱을 반환합니다.
- sqrt(double a) → double
설명: a의 제곱근을 반환합니다.
- cbrt(double a) → double
설명: a의 세제곱근을 반환합니다.
- max()
- max(int a, int b) → int,
- max(double a, double b) → double,
- max(float a, float b) → float,
- max(long a, long b) → long
설명: 두 값 중 더 큰 값을 반환합니다.
- min()
- min(int a, int b) → int
- min(double a, double b) → double
- min(float a, float b) → float
- min(long a, long b) → long
설명: 두 값 중 더 작은 값을 반환합니다.
- random() → double
설명: 0.0(포함) 이상 1.0(제외) 미만의 난수를 반환합니다.