我试图写一个带有两个输入值的sum数组函数。逐渐添加第一个输入值,直到达到第二个输入的值。例如,如果lowerLimit是&#39; 2&#39;而上限是&#39; 5&#39;总和将是2 +(2 + 1)+(2 + 2)+(2 + 3)+(2 + 4)+(2 + 5)= 27.我尝试使用变量&# 39; I&#39;这是添加到lowerLimit并逐渐上升直到(i <=(upperLimit - lowerLimit)但我不确定如何写和数组,或者如果和数组甚至是接近这个的最佳方法。 谢谢你的帮助。
Q7显示
Q7
<!-- Question 7 Start -->
<div role="tabpanel" class="tab-pane tab-pane active" id="q6">
<div class="row">
<div class="col-md-12">
<pre>
问题7代码:
</pre>
</div>
<div class="col-md-12">
<!-- button -->
<button id="button" class="btn btn-default" type="button">Question Seven Solution</button>
</div>
<div class="col-md-12">
<!-- result -->
<div id="result"></div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
var lowerLimit = 0;
var upperLimit = 0;
function range(lowerLimit, upperLimit){
var lowerLimit = parseInt(prompt("What number would you like to being with?"));
if (isNaN(lowerLimit)) {
alert("That's not a number, please retry.");
var lowerLimit = prompt("Please re-enter a number.");
}
var upperLimit = parseInt(prompt("What number would you like to end with?"));
if (isNaN(upperLimit)) {
alert("That's not a number, please retry.");
var upperLimit = prompt("Please re-enter a number.");
}
/* var arr = [upperLimit, lowerLimit, i];
for(i = 1; i <= (upperLimit - lowerLimit); i++){
var equation = lowerLimit + (lowerLimit+i);
}*/
//ends function
}
//ends document ready function
});
</script>
答案 0 :(得分:1)
数组的用途是什么? 您可以直接添加它们并在不使用数组的情况下输出...
试试这段代码:
var sum=lowerLimit;
for(i=1; i<=upperLimit; i++){
sum += (lowerLimit+i);
}
答案 1 :(得分:0)
var sum=lowerlimit;
for(i=1; i<=upperLimit; i++){
sum += (lowerLimit+i);
}