简体   繁体   English

我想编写javascript代码以获得额外的倒计时

[英]I want to write javascript code to get a addition countdown

so basically this the prompt: 所以基本上这个提示:

Addition countdown 加法倒计时

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 . 你输入一个数字,代码应该在倒计时添加一个数字,例如,如果用户输入10,那么结果应该是: 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 ) 但我继续得到这样的东西:4 + 3 + 72 +1 +3( 假设4是用户输入的数字

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. 您可以在while循环之外的一个变量中保留total。

 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--; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM