예제
<script>
/*
[문제]
숫자 1부터 10 사이의 랜덤 숫자 두 개를 저장합니다.
이어서 1부터 2 사이의 랜덤 숫자를 하나 더 생성합니다.
생성된 숫자가 1이면 두 수의 합을, 2이면 두 수의 곱을 출력합니다.
위 과정을 총 5번 반복하여 출력하시오.
*/
/*
[출력예시]
5 7 2 35
1 6 1 7
8 9 1 17
8 2 2 16
8 10 1 18
*/
</script>
HTML
복사
정답
<script>
/*
[문제]
숫자 1부터 10 사이의 랜덤 숫자 두 개를 저장합니다.
이어서 1부터 2 사이의 랜덤 숫자를 하나 더 생성합니다.
생성된 숫자가 1이면 두 수의 합을, 2이면 두 수의 곱을 출력합니다.
위 과정을 총 5번 반복하여 출력하시오.
*/
/*
[출력예시]
5 7 2 35
1 6 1 7
8 9 1 17
8 2 2 16
8 10 1 18
*/
// [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 = r * r2;
}
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 = r * r2;
}
document.write(a, "<br>");
i += 1;
}
</script>
HTML
복사


