javascript

javascript_제어문(반복문_연습문제)_22.04.22(day03)

양빵빵 2022. 4. 22. 12:08

 

 

 



//x ~ y 까지의 누적합 : total

var x = +prompt('1.정수를 입력하세요.') ;
var y = +prompt('2.정수를 입력하세요.');
var total = 0 ;
var count = 0 ;

while(x <= y){
    if( x <=y ) {
        count++;
    }
    total += x;
    x++;    
}

alert(`${x-count} ~ ${y}까지의 누적합: ${total}`);
 
======================== ↓ 정답
 
var x = +prompt('첫번째 숫자: ');
var y = +prompt('두번째 숫자: ');

var total = 0;
var n = x;
while (n <= y) {
    total += n;
    n++
}
console.log(`${x} ~ ${y}까지의 누적합: ${total}`);
 

===================== 먼저 입력된 수가 나중에 입력된 수보다 클 때 if와 값 스위칭을 하여 코딩

 

var x = +prompt('첫번째 숫자: ');
var y = +prompt('두번째 숫자: ');

//값 스위칭
if (x > y) {
    var t = x;
    x = y;
    y = t;
}

var total = 0;
var n = x;
while (n <= y) {
    total += n;
    n++
}
alert(`${x} ~ ${y}까지의 누적합: ${total}`);