Search

배열3_문제05_배열두개_홀수

대분류
STEP05 일차배열
문제 난이도
LV02
소분류
일차배열3_문제

영상

문제

<script> /* [문제] 배열 a와 배열 b에 랜덤 숫자(1~100)를 다섯 개씩 저장하고, 배열 a의 홀수 합과 배열 b의 홀수 합을 비교해서 더 큰 값을 출력하시오. 단, 서로 같으면 둘 다 출력하시오. [예시] a = 28, 79, 47, 70, 36 b = 63, 4, 45, 54, 87 totalA = 126 totalB = 195 195 */ let a = []; let b = []; </script>
Java
복사

해설

<script> /* [문제] 배열 a와 배열 b에 랜덤 숫자(1~100)를 다섯 개씩 저장하고, 배열 a의 홀수 합과 배열 b의 홀수 합을 비교해서 더 큰 값을 출력하시오. 단, 서로 같으면 둘 다 출력하시오. [예시] a = 28, 79, 47, 70, 36 b = 63, 4, 45, 54, 87 totalA = 126 totalB = 195 195 */ let a = []; let b = []; for(let i=0; i<5; i++) { a.push(Math.floor(Math.random() * 100) + 1); b.push(Math.floor(Math.random() * 100) + 1); } document.write("a = " + a + "<br>"); document.write("b = " + b + "<br>"); let totalA = 0; let totalB = 0; for(let i=0; i<5; i++) { if(a[i] % 2 != 0) { totalA += a[i]; } if(b[i] % 2 != 0) { totalB += b[i]; } } document.write("totalA = " + totalA + "<br>"); document.write("totalB = " + totalB + "<br>"); if(totalA > totalB) { document.write(totalA + "<br>"); } else if(totalA < totalB) { document.write(totalB + "<br>"); } else if(totalA == totalB) { document.write(totalA + ", " + totalB + "<br>"); } //-------------------------------------------- a = []; b = []; totalA = 0; totalB = 0; let i = 0; while(i < 5) { a.push(Math.floor(Math.random() * 100) + 1); b.push(Math.floor(Math.random() * 100) + 1); i += 1; } document.write("a = " + a + "<br>"); document.write("b = " + b + "<br>"); i = 0; while(i < 5) { if(a[i] % 2 != 0) { totalA += a[i]; } if(b[i] % 2 != 0) { totalB += b[i]; } i += 1; } document.write("totalA = " + totalA + "<br>"); document.write("totalB = " + totalB + "<br>"); if(totalA > totalB) { document.write(totalA); } else if(totalA < totalB) { document.write(totalB); } else if(totalA == totalB) { document.write(totalA + ", " + totalB); } </script>
Java
복사