[Java] math
카테고리: Java
태그: coding Programming Java
math
API 란?
- Application programming Interface 은 응용프로그램에서 사용할 수 있도록
- 운영체제나 프로그래밍 언어가 제공하는 기능을 제어할 수 있도록 만든 인터페이스를 뜻 한다
- 쉽게 말해 우리가 구현할 수 없거나 구현하기 번거로운 기능들을 JDK를 설치하면 사용할 수 있도록
- 제공해놓은 소스코드(클래스나 인터페이스)들을 의미한다
- 더 쉽게 말해 누가 작성해놓은 소스 코드이니 가져다 쓰는 방법을 본다는 말이다
- 모든 코드를 우리가 다 외울 수 없으니 API 문서를 별도로 제공해 주고 있다
java.lang.Math
- Math 클래스는 수학에서 자주 사용하는 상수들과 함수들을 미리 구현해놓은 클래스이다
- 모든 매소드는 static 메소드로 작성되어 있다
- (객체의 상태를 관리하지 않고 기능만을 제공하는 경우 메모리를 효율적으로 사용하기 위해 자주 사용되는 기법이다)
절대값 출력
package com.ohgiraffers.section03.math;
public class Application1 {
public static void main(String[] args) {
/*1-1. 클래스의 풀네임을 다 적은 경우 */
System.out.println("-7의 절대갑 : " + (java.lang.Math.abs(-7)));
/* 1-2. import를 해서 사용 */
System.out.println("1.25의 절대값 : " + (Math.abs(1.25)));
/* 2. 최대값, 최소값 출력 */
System.out.println("10과 20중 더 작은 것은? " + Math.min(10,20));
System.out.println("20과 30중 더 큰 것은? " + Math.max(20,30));
System.out.println("원주ㅇ율 : " + Math.PI); //원주율은 그냥 PI로 불러오기만 하면 된다.
/* 3.난수 출력 */
System.out.println("난수 발생 : " + Math.random()); // 계속 변경
//난수 발생 : 0.30889189648231863
//난수 발생 : 0.3802547003732778
}
}
- 출력값
-7의 절대갑 : 7
1.25의 절대값 : 1.25
10과 20중 더 작은 것은? 10
20과 30중 더 큰 것은? 30
원주율 : 3.141592653589793
난수 발생 : 0.580094873340106
난수의 활용
- Math.random()을 이용해 발생한 난수는 0부터 1전 까지의 실수 범위의 난수값을 반환한다
- 필요에 따라 정수 형태의 값을 원하는 범위만큼 발생시켜야 하는 경우도 존재한다
일하는 범위의 난수를 구하는 공식
- (int)(Math.random * 구하려는 난수의 갯수) + 구하려는 난수의 최소값
package com.ohgiraffers.section03.math;
public class Application2 {
public static void main(String[] args) {
/* 1. 0~9까지의 난수 발생 */
int random1 = (int)(Math.random() * 10 );
System.out.println("0부터 9사이의 난수 : " + random1);
/* 2. 1~10까지의 난수 발생 */
int random2 = (int)(Math.random() * 10 ) + 1;
System.out.println("0부터 10사이의 난수 : " + random2);
/* 3. 10 ~ 15까지의 난수 발생 */
int random3 = (int)(Math.random() * 6) + 10;
System.out.println("10부터 15사이의 난수 : " + random3);
}
}
- 출력값
0부터 9사이의 난수 : 4
0부터 10사이의 난수 : 2
10부터 15사이의 난수 : 13
java.util.Random 클래스를 활용하여 사용자 범위의 난수를 발생시킬 수 없다
- java.util.Random 클래스
- java.util.Random 클래스 nextInt() 매소드를 이용한 난수 발생
- nextInt(int bound) : 0부터 매개변수로 전달 받은 정수 범위까지의 난수를 발생시켜서 정수 형태로 반환
package com.ohgiraffers.section03.math;
import java.util.Random;
public class Application3 {
public static void main(String[] args) {
/*random.nextInt(구하려는 난수의 갯수) + 구하려는 난수의 최소값 */
Random random = new Random();
/* 1. 0부터 9까지 난수발생 */
int randomNum = random.nextInt(10);
System.out.println("0부터 9까지의 난수 ? " + randomNum);
/* 2. 1부터 10까지 난수발생 */
int randomNum1 = random.nextInt(10) + 1;
System.out.println("1부터 10까지의 난수 ? " + randomNum1);
/* 3. 20부터 45까지의 난수 발생 */
int randomNum2 = random.nextInt(26) + 20;
System.out.println("20부터 45까지의 난수 ? " + randomNum2);
/* 4.-280 ~ 127 까지의 난수발생 */
// int randomNum3 = random.nextInt(256) - 128;
int randomNum4 = new Random().nextInt(256) - 128; // 객체를 생성하자마자 바로 매소드 호출 가능
System.out.println("128~127까지의 난수발생" + randomNum4);
}
}
- 출력값
0부터 9까지의 난수 ? 1
1부터 10까지의 난수 ? 3
20부터 45까지의 난수 ? 35
128~127까지의 난수발생9
댓글 남기기