我正在尝试学习使用for()循环来计算从一个数字到另一个数字的整数(整数)。到目前为止,这是我的代码:
function processLoop(earlier,later) {
earlier = 0;
later = 0;
count = 0;
for (i = earlier; i <= later; i++) {
count = count + i;
};
return count;
};
我应该有这两个参数,但它没有运行。我觉得我不够清楚,所以这是我的指示:
我对此很新,我不确定我应该在这做什么。谢谢你的帮助...
答案 0 :(得分:2)
无论您传入的是什么,都要将参数设置为零。
摆脱那些台词。
另外,使用var
定义局部变量。
function processLoop(earlier,later) {
var count = 0;
for (var i = earlier; i <= later; i++) {
count = count + 1;
};
return count;
};
答案 1 :(得分:0)
如果earlier
和later
是默认值,可以在参数传递给函数时设置,可以使用OR
||
运算符。您还应该使用++count
替换count = count + i
来返回earlier
和later
之间的差异。也为<
运算符替换了<=
运算符。
function processLoop(earlier, later) {
var earlier = earlier || 0,
later = later || 0,
count = 0;
// use `for` loop only if `earlier` does not equal `later`
// and `later` is greater than `earlier`
if (typeof earlier === "number" && typeof later === "number") {
if (earlier !== later && later > earlier) {
for (i = earlier; i < later; i++) {
++count;
};
} else {
return new Error("earlier is not greater than later")
}
return count;
} else {
return new TypeError("earlier or later is not a number")
}
};
console.log("no parameters passed to processLoop:", processLoop()
, "\n10 passed as later:", processLoop(null, 10)
, "\ndifference between 25 and 50:", processLoop(25, 50)
, "\ndifference between 5 and 6:", processLoop(5, 6)
, "\ndifference between 1 and 1:", processLoop(1, 1)
, "\nearlier or later is not a number", processLoop("a", "b")
);
答案 2 :(得分:0)
function processLoop(earlier,later) {
var count = 0;
for (i = earlier; i < later; i++) {
count++;
};
document.getElementById("demo").innerHTML = count;
};
<html>
<body>
<button onclick="processLoop(1,3)">Click me</button>
<p id="demo"></p>
</body>
</html>
请勿在函数内将参数值设置为zero
。如果您想在earlier
和later
之间进行计数,而无需包含earlier
,请使用i < later
代替i <= later
。
function processLoop(earlier,later) {
count = 0;
for (i = earlier; i < later; i++) {
count++;
};
return count;
};
答案 3 :(得分:0)
您需要尝试解释解释问题的答案,因为它有点模糊。如果要计算实数x和y之间的整数,了解间隔是打开还是关闭非常重要。
我不支持编写代码,但在这种情况下,它是最好的答案。以下代码在封闭的实际间隔中计算整数,[更早,更晚]:
function countIntegers(earlier, later)
{ earlier = Math.ceil(earlier);
later = Math.floor( later);
for( var i = earlier, count = 0; i <= later; ++i, ++count);
return count;
}
您可能需要查找Math.ceil
和Math.floor
所做的事情以及尝试打开和关闭间隔的组合,直到找到标记正确的那个。享受: - )