JAVA/java 공부

[JAVA] Math.method

congs 2023. 3. 25. 15:48

Math.method

: 수학적 기능을 하기 위한 클래스

 

double num1 = 5.623456;

//Math.round : 정수가 나오는 반올림 (소수점을 선택하는 기능x)
System.out.println(Math.round(num1)); // 결과는 6
	
//Math.ceil : 올림, Math.floor : 버림
System.out.println(Math.ceil(num1)); //나오는 자료형이 double // 결과는 6.0
System.out.println(Math.floor(num1)); // 결과는 5.0
		
//Math.max : 최대값, Math.min : 최소값
System.out.println(Math.max(5, 3)); // 결과는 5
System.out.println(Math.min(5, 3)); // 결과는 3
		
//Math.abs : 절대값
System.out.println(Math.abs(-5)); // 결과는 5
	
//Math.pow : 제곱, , 
System.out.println(Math.pow(2, 3)); // 결과는 8.0

//Math.sqrt : 제곱근(루트씌우기)
System.out.println(Math.sqrt(25)); // 결과는 5

 

⭐ (int)(Math.random()*n)+start

  • n = startNum - lastNum +1 (개수)
  • 나오는 수가 double ⇒ (int)이용하여 정수 형태로 형 변환
  • 0~1을 0~10으로 바꾸기 위해 (Math.random()*1)
  • 시작 값을 1로 만들기 위하여 +1 시작 값
  • 마지막 값이 < (포함하지 않음) !!!!
//Math.random : 0~1 사이의 랜덤값 (double의 값(0~1사이의 실수)으로 추출)
System.out.println(Math.random()); // 결과는 0.3762191102244563

//Math.random 이용1~10까지 중 랜덤값 추출
//(int)(Math.random()*(StartNum-lastNum+1))+startNum
//(int)(Math.random()*10)+1 : 1~10까지의 랜덤값
			
int random = (int)(Math.random()*10)+1; 
System.out.println(random);	

//나오는 수가 double이므로 (int)이용하여 정수 형태로 형변환 
//+ 0~1을 0~10으로 바꾸기위해 (Math.random()*10)	
//+ 시작값을 만들기위하여 +시작값 : +1

 

⭐ Random class 

  • Math.random과 동일한 효과
int a = new Random().nextInt(n) + startNum;

'JAVA > java 공부' 카테고리의 다른 글

[JAVA] class 클래스 구성요소  (0) 2023.03.25
[JAVA] 조건문 If문 / switch문  (0) 2023.03.25
[JAVA] Scanner 스캐너  (0) 2023.03.25
[JAVA] escape sequence : \  (0) 2023.03.25
[JAVA] printf() 사용 : %s  (0) 2023.03.25