如何将所有数字相加,直到输入数字(包括输入数字)

How to add up all numbers up to, and including, the input number?

本文关键字:数字 输入 包括      更新时间:2023-09-26

我是一个完全的JS菜鸟,我正在尝试使输入一个输入后,0和该输入之间的所有数字相加,包括输入。这是我试图完成的基本伪代码,但我无法弄清楚?

get count from user
loop up to count{
     add current number to sum
}
display sum
display breakline
loop up to count with a different loop type{
    add current number to sum
}
display sum

最快的方法是添加一个序列(不需要循环):

let sum = input * (input + 1) / 2

有关详细信息,请参阅此链接。

你可以尝试这样的事情:

// input would be the number that the user will enter
var input = 10;
// the starting number is 0.
var temp = 0;
// the sum.
var sum = 0;
// while the temp would be less or equal to the input,
// then we will add the temp to the sum and we increase it by 1.
// This way, when temp would be equal to imput+1, the statement in 
// the while loop would be false, and the statements in the while loop 
// wouldn't be executed. At this moment, the sum would hold the sum of 
// the integers numbers in the range [0,input].
while(temp<=input)
{
    sum+=temp;
    temp++;
}

至于显示的部分完全取决于您要显示结果的位置。如果要在控制台上显示它。

console.log(sum);

如果要在警报框中显示它。

alert(sum);

等。

var sum = 0;
var input = getCountFromUser(); //However you do it.
for (var j = 1; j <= input; j++) {
  sum += j;
}

或者,更短一些:

var sum = 0, input = getCountFromUser(), j = 1;
for (; j <= input;) {
  sum += j++;
}

这是显示您想要的完整代码:

<HTML>
<HEAD>
<TITLE>JavaScript Form - Input Text Field</TITLE>
<SCRIPT Language="JavaScript">
<!--//
function showAndClearField(frm){
  if (frm.num.value == "")
      alert("Hey! You didn't enter anything!")
  else{
  		var result = 0;
		var input = frm.num.value; //However you do it.
		for (var i = 1; i <= input; i++) {
		  result += i;
		}
      alert("Result: " + result)
  }
  frm.firstName.value = ""
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="test">
<H2>Enter a number.</H2>
<INPUT TYPE="Number" NAME="num"><BR><BR>
<INPUT TYPE="Button" Value="Show and Clear Input" onClick="showAndClearField(this.form)">
</P>
</FORM>
</BODY>
</HTML>