[JS]07(1)Math.random()(+Math.floor())

2u·2023년 3월 8일

JavaScript

목록 보기
7/43
post-thumbnail

1. Math.random

:JS에서 난수를 생성하기 위해서는, Math.random()함수를 사용한다.
: 이 함수는 0~1(1은 미포함) 구간에서 부동소수점의 난수를 생성한다.

const rand1 = Math.random();
const rand2 = Math.random();
const rand3 = Math.random();

document.write(rand1 + '<br>');
document.write(rand2 + '<br>');
document.write(rand3 + '<br>');

-> 값 :
0.9366516672091441
0.6566869900022965
0.05651155562996357

2. 범위를 지정한 난수 생성하기

:Math.random()함수는 0~1 사이의 부동소수점 난수를 생성한다. 이때, 정수인 난수를 생성하려면?

⭐️Math.random() + Math.floor()⭐️

: Math.floor() 함수는 소수점 1번째 자리를 버림하여 정수를 리턴하는 함수이다.
😎 참고
반올림(round) : 소수점 지정
올림(ceil) : 음수 지정
내림(floor) : 자리수 지정

//(1) 0 <= random <= 1
const rand1 = Math.random();
docuemnt.write('(1)' + rand1 + '<br>');
//-> 값 : 0.6942110239621544 
// 랜덤의 0~1사이의 부동소수점 난수 

//(2) 0
const rand2 = Math.floor(Math.random());
document.write(rand2);
//-> 값: 0
// Math.floor()함수는 소수점 1번째자리 이후의 숫자를 버림하고, 정수를 리턴합니다.
// Math.floor()함수 결과는 0~0.999999....인 숫자를 리턴하기 때문에,
// Math.floor(Math.random()0의 결과는 항상 0입니다.

//(3) 0 <= random <=9
const rand3 = Math.floor(Math.random() * 10);
document.write(rand3);
//-> 값:0~9사이의 정수
// Math.random() -> 0~0.999999....
// Math.random() * 10 -> 0~9.9999...

//(4) 0<=random<=99
cosnt rand4 = Math.floor(Math.random() * 100);
document.Write(and4);
//-> 값: 0~99 사이의 정수

//(5) 0<=random<=100
const rand5 = Math.floor(Math.random() * 101);
document.write(rand5);
//-> 값 0~100 사이의 정수

//(6) 1<=random<=10
const rand6 = Math.floor(Math.random() * 11)+1;
document.writh(rand6);
// -> 값: 1~10사이의 정수
// 최소값을 지정하고 싶을 때는 Math.random()*(max-min+1) 값을 계산하고
// 소수점 이하를 버림한다. 
// 그리고 min을 더해준다. 
// Math.floor(Math.random() * (10-1+1)) +1 

//(7) 2<=random<=5
const rand7 = Math.floor(Math.random() * 4)+2;
document.write(rand7);
//-> 값: 2~5사이의 정수
// Math.floor(Math.random()*(5-2+1))+2

3. 난수 생성 함수 만들기(범위 지정)

1) min <= number <= max (max 값 포함) 😏

: min~max 값까지의 정수 랜덤 넘버를 만들어주는 함수

function rand(min, max){
return Math.floor(Math.random()*(max-min+1)+min;
}

document.writhln(rand(1, 3));
//-> 값: 1~3사이의 정수 반환
document.writhln(rand(77, 88));
//-> 값: 77~88사이의 정수 반환

2) min <= number < max(max 값 불포함) 😏

: max값을 포함하지 않는, min~max 값까지의 정수 랜덤 넘버를 만들어주는 함수

function rand(min, max){
 retrun Math.floor(Math.random()*(max-min))+min;
}

document.writeln(rand(1, 3));
//-> 값: 1이상 3미만인 정수값 반환
document.writhln(rand(77, 88));
//-> 값: 77이상 88미만인 정수값 반환

0개의 댓글