GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

No menu could be recovered. Follow the blue links in the page.

This view

  • Original page
  • New address

GeezerVison is showing ko.javascript.info — min과 max 사이에 있는 임의의 숫자 생성하기

  • 튜토리얼
  • 코어 자바스크립트
  • 자료구조와 자료형
  • 숫자형
돌아가기

min과 max 사이에 있는 임의의 숫자 생성하기

중요도: 2

내장 함수 Math.random()은 0부터 1까지의(1은 포함되지 않음) 랜덤한 값을 생성합니다.

random(min, max)함수를 작성하여 min부터 max까지 임의의 부동 소수점 숫자를 생성합니다(max는 포함되지 않음).

예시를 살펴봅시다.

alert( random(1, 5) ); // 1.2345623452
alert( random(1, 5) ); // 3.7894332423
alert( random(1, 5) ); // 4.3435234525

We need to “map” all values from the interval 0…1 into values from min to max.

이 작업은 두 단계로 이루어집니다.

  1. 0과 1 사이의 임의의 숫자에 max-min를 곱하면 가능한 값의 간격이 0..1에서 0..max-min으로 증가합니다.
  2. Now if we add min, the possible interval becomes from min to max.

The function:

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

alert( random(1, 5) );
alert( random(1, 5) );
alert( random(1, 5) );
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.