TIL # 21 (JS 21)

Mikyung Lee·2021년 1월 17일
0
post-thumbnail

21. Number

keyword : Math.round / Math.ceil / Math.floor / Math.random()

반올림 함수

console.log(Math.round(2.5));
console.log(Math.round(2.49));
console.log(Math.round(2));
console.log(Math.round(2.82));

올림 함수

console.log(Math.ceil(2.5));
console.log(Math.ceil(2.49));
console.log(Math.ceil(2));
console.log(Math.ceil(2.82));

내림 함수

console.log(Math.floor(2.5));
console.log(Math.floor(2.49));
console.log(Math.floor(2));
console.log(Math.floor(2.82));

랜덤 함수 :
0.0000000000000000에서 0.9999999999999999 사이의 값에서 랜덤수를 제공한다

var randomNumber = Math.random();
console.log(randomNumber)

Assignment

앞으로 랜덤함수를 쓸 일이 정말 많습니다.
그런데 Math.random()으로는 내가 원하는 범위의 랜덤수를 얻을 수가 없습니다.
항상 0.0000000000000000에서 0.9999999999999999 사이 값에서만 return해주기 때문이죠.
최소(min), 최대값(max)을 받아 그 사이의 랜덤수를 return하는 함수를 구현해주세요.

  • 함수는 짧지만, 이번에는 수학의 뇌를 조금 써야 하는 assignment입니다.
function getRandomNumber(min, max) {
  return Math.floor(Math.random() * ((max + 1) - min)) + min;
}


링크 참고하기

❔❕ ((max + 1) - min)) + min 이 부분이 이해가 가지 않았는데 숫자를 대입해보니 이해가 간다. 예를 들어 min = 3, max = 7이라고 하자. random 값은 0과 1 사이의 값이니까. max-min = 4 그럼 0부터 4 사이의 정수가 나온다. 4는 포함하지 않으므로 +1을 해준다. 그러면 0부터 5까지의 랜덤 정수가 나와서. 0,1,2,3,4가 나올 수 있다. 근데 그럼 min=3보다 작으므로 min =3 값을 끝에 더해줘야 한다. 그러면 3,4,5,6,7이 랜덤값으로 나온다.


(max+1)- min 을 해주면 왜 안될까 봤더니 max 값이 0 부터 시작하는거라 min을 빼주면 설정된 min값 보다 더 내려갈 수도 있다. 그래서 최소값으로 min을 더해주는게 솔루션!

profile
front-end developer 🌷

0개의 댓글