Web/Javascript

[Javascript] 모던 JS 5.2 (숫자형) 과제

동띵 2022. 5. 23. 15:10

1) 수를 입력받아 덧셈하기

let a = +prompt("첫 번째 수를 입력하세요", 0);
let b = +prompt("두 번째 수를 입력하세요", 0);

console.log(a+b);

 

2) 6.35.toFixed(1) == 6.3인 이유는 무엇일까요?

-> Math.round(6.35 * 10) / 10

 

3) 숫자를 입력할 때까지 반복하기

function readNumber() {
    let input;
    do {
        input = prompt("숫자를 입력하세요", 0);
    } while(!isFinite(input));

    if (input === null || input === '') return null;
    return +input;
}

 

4) An occasional infinite loop

-> 0.2를 소수점 20번째 자리까지 출력해보면

0.20000000000000001110가 나온다.
따라서 0.2를 계속 더해도 10이 나오지 않기 때문에 while문이 끝나지 않는 것이다.

 

5) A random number from min to max

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

 

6) A random number from min to max

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