[英]Why does this while loop loop forever?
I have tried looking at documentation and could not figure it out.我试过查看文档但无法弄清楚。 My while loop does not stop and prints "ya" forever.我的 while 循环不会停止并永远打印“ya”。 What am I doing wrong?我究竟做错了什么?
var ya = 1;
Formitivegrades = [100, 95, 100, 85, 100]
Formitiaveav1 = Formitivegrades[0] + Formitivegrades[1] + Formitivegrades[3] + Formitivegrades[4] + Formitivegrades[2]
Formitiaveav2 = Formitiaveav1 / 5
sumgrades = [100]
sumav1 = ya + sumgrades[0]
sumav2 = sumav1 / 2
averge = .4 * Formitiaveav2 + .6 * sumav2
while(averge < 95){
console.log(ya)
ya++;
}
console.log(averge)
Don't think of the equal sign =
as an equality that is guaranteed forever, the way it is in mathematics.不要将等号=
视为永远保证的相等性,就像在数学中那样。 In programming it is a one-time assignment.在编程中,这是一项一次性任务。 An assignment statement gives a variable a new value at that moment in time only.赋值语句仅在该时刻为变量赋予新值。 If they change values afterwards the equality can be broken.如果他们之后更改值,则可以打破平等。
If ya
is updated that does not cause sumav1
to be recalculated.如果更新了ya
,则不会导致重新计算sumav1
。 Nor does sumav2
change whenever sumav1
changes, nor avrge
when sumav2
changes. sumav2
发生变化时sumav1
也不会发生变化, avrge
发生变化时sumav2
也不会发生变化。 averge
keeps the same value forever unless you explicitly update it. averge
永远保持相同的值,除非您明确更新它。
To that end, you need to recompute all of the variables each time you change ya
.为此,每次更改ya
时都需要重新计算所有变量。 That way averge
can eventually reach 95
and cause the loop to end.这样averge
最终可以达到95
并导致循环结束。
while(averge < 95){
console.log(ya)
ya++;
sumav1 = ya + sumgrades[0]
sumav2 = sumav1 / 2
averge = .4 * Formitiaveav2 + .6 * sumav2
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.