영상
문제
<script>
/*
[문제]
1~10 사이의 숫자를 랜덤으로 2개 저장하고,
작은 숫자부터 큰 숫자까지의 합을 출력하는 함수를 만드시오.
[예시]
5, 3 ==> 3 + 4 + 5
2, 6 ==> 2 + 3 + 4 + 5 + 6
*/
let r1 = Math.floor(Math.random() * 10) + 1;
let r2 = Math.floor(Math.random() * 10) + 1;
</script>
Java
복사
해설
<script>
/*
[문제]
1~10 사이의 숫자를 랜덤으로 2개 저장하고,
작은 숫자부터 큰 숫자까지의 합을 출력하는 함수를 만드시오.
[예시]
5, 3 ==> 3 + 4 + 5
2, 6 ==> 2 + 3 + 4 + 5 + 6
*/
function printTotal(r1, r2) {
if(r1 > r2) {
let temp = r1;
r1 = r2;
r2 = temp;
}
let total = 0;
for(let i=r1; i<=r2; i++) {
document.write(i);
if(i < r2) {
document.write(" + ");
}
total += i;
}
document.write(" = " + total);
}
let r1 = Math.floor(Math.random() * 10) + 1;
let r2 = Math.floor(Math.random() * 10) + 1;
printTotal(r1, r2);
</script>
Java
복사