점검
<script>
/*
[문제]
1부터 10 사이의 랜덤 숫자 두 개를 저장합니다.
이어서 1부터 2 사이의 랜덤 숫자를 하나 더 생성합니다.
생성된 숫자가 1이면 앞의 수에서 뒤 수를 뺀 값을,
2이면 뒤에 수에서 앞의 수를 뺀 값을 출력합니다.
위 과정을 총 5번 반복하여 출력하시오.
*/
/*
[출력예시]
6 9 2 3
1 4 2 3
9 8 1 1
10 5 2 -5
6 9 1 -3
*/
</script>
HTML
복사
정답
<script>
/*
[문제]
1부터 10 사이의 랜덤 숫자 두 개를 저장합니다.
이어서 1부터 2 사이의 랜덤 숫자를 하나 더 생성합니다.
생성된 숫자가 1이면 앞의 수에서 뒤 수를 뺀 값을,
2이면 뒤에 수에서 앞의 수를 뺀 값을 출력합니다.
위 과정을 총 5번 반복하여 출력하시오.
*/
/*
[출력예시]
6 9 2 3
1 4 2 3
9 8 1 1
10 5 2 -5
6 9 1 -3
*/
// [for문]
for(let i = 0; i < 5; i++) {
let r = Math.floor(Math.random() * 10) + 1;
let r2 = Math.floor(Math.random() * 10) + 1;
document.write(r, " ", r2, " ");
let s = Math.floor(Math.random() * 2) + 1;
document.write(s, " ");
let a = 0;
if(s == 1) {
a = r - r2;
}
if(s == 2) {
a = r2 - r;
}
document.write(a, "<br>");
}
document.write("<br>");
// [while문]
let i = 0;
while(i < 5) {
let r = Math.floor(Math.random() * 10) + 1;
let r2 = Math.floor(Math.random() * 10) + 1;
document.write(r, " ", r2, " ");
let s = Math.floor(Math.random() * 2) + 1;
document.write(s, " ");
let a = 0;
if(s == 1) {
a = r - r2;
}
if(s == 2) {
a = r2 - r;
}
document.write(a, "<br>");
i += 1;
}
</script>
HTML
복사


