如何将所有数字相加,直到输入数字(包括输入数字)
How to add up all numbers up to, and including, the input number?
我是一个完全的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>
相关文章:
- 是否可以在数字输入框中的小按钮中添加事件侦听器
- 用于数字输入的正则表达式
- AngularJs:在数字输入字段中设置验证的条件最小值和最大值
- 敲除:如何对两个数字输入进行双向绑定
- 在数字输入上按回车键时提交
- 如何显示正好 2 位数字的 html 数字输入的输入值
- 如何使用鼠标或触摸更改数字输入字段
- 为数字输入添加特殊字符
- 在一些Android设备/Chrome上,HTML5数字输入中没有小数点
- 仅HTML输入除^之外的数字输入
- 如何处理 jQuery 中的数字输入更改
- 使用 js 禁用文本输入中的数字输入
- 角度JS数字输入和默认值
- 如何根据数字输入的总和限制数字输入
- 如何更改数字输入的格式
- 从给定的最大数字中减去并输出数字输入值
- 如何使此数字输入接受逗号
- 如何将加号和减号附加到数字输入和更新值
- 在我更改数字输入时获取要更改的范围的内容
- 多个数字输入,jquery .each 如果 val() 大于,则将类添加到元素