so basically this the prompt:
you enter a number and the code should be adding a number while countingdown, for example if the user enter 10, then the result should be: 10 + 9 + 8 + 7 + 6 + 5 + 4 +3 +2 +1=55
.
This is what I have so far:
var num = Number(prompt("Enter a Number Greater than zero"));
while (num > 0){
first = num;
second = num-=1;
document.write(first + " +" + second + " +");
value = first + num;
document.write(value)
num--;
}
but I keep on getting something like this: 4 +3 +72 +1 +3 ( let's say 4 is the number the user inputs )
I'm stuck can someone please help me????!!
You could change the algorithm a bit, because for the first value, you need no plus sign for the output.
var num = Number(prompt("Enter a Number Greater than zero")), value = 0; document.body.appendChild(document.createTextNode(num)); value += num; num--; while (num > 0) { document.body.appendChild(document.createTextNode(' + ' + num)); value += num; num--; } document.body.appendChild(document.createTextNode(' = ' + value));
You can keep total in one variable outside of while
loop.
var num = Number(prompt("Enter a Number Greater than zero")); var total = 0; while (num > 0) { total += num; document.body.innerHTML += (num == 1 ? num + ' = ' + total : num + ' + '); num--; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.