코딩하는 둥둥

[Java] Math.random() 본문

Backend/Java

[Java] Math.random()

둥둥 2022. 4. 25. 22:07
728x90
Math.random()

Math.random() 함수는 0.0 이상 1.0 미만의 double 반환하는 함수이다.

주로 랜덤 한 값(난수)을 만드는 데 사용된다.

출처 : https://docs.oracle.com/javase/8/docs/api/

 

실행할 때마다 랜덤 한 값이 출력되며 특정한 범위의 값을 원할 경우 함수에 해당 범위 값을 곱해주면 된다.

예를 들어서 0에서 10사이의 값을 구하려고 할 때는 random함수에 10을 곱하면 해당 범위의 값 중에서 랜덤 한 값이 출력된다.

 

기본 반환값이 double(실수형) 이기 때문에 int(정수형)으로 사용하고 싶을 경우 형 변환이 필요하다

정수형으로 형변환을 했을 때는 0부터 출력되기 때문에 1부터 출력하고 싶을 때는 1을 더해줘야 한다.

마찬가지로 10부터 시작하고 싶을 때는 10을 더해주면 된다.

 


  • 참고 링크

https://www.javatpoint.com/java-math-random-method#:~:text=random()%20is%20used%20to,the%20magnitude%20of%20the%20range.

 

Java Math.random() Method with Examples - Javatpoint

Java Math.random() Method with Examples on abs(), min(), max(), avg(), round(), ceil(), floor(), pow(), sqrt(), sin(), cos(), tan(), exp() etc.

www.javatpoint.com

https://www.w3schools.com/js/js_random.asp

 

JavaScript Random

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

728x90

'Backend > Java' 카테고리의 다른 글

[ JAVA ] 배열의 정렬 : Arrays.sort() VS Arrays.parallelSort()  (0) 2022.05.03
[ JAVA ] 배열(Array)  (0) 2022.05.03
[ Java ] Scanner  (0) 2022.03.26
Escape  (0) 2022.03.26
Module과 module-info.java (Java 11버전~)  (0) 2022.03.25