我正在嘗試實作 3、4、5 的輸出。但是,我只得到 3,5 .it 跳躍/跳過一個數字。不知道為什么。鑒于我的代碼如下。幫助我修復錯誤,請讓我知道它為什么會發生以及我在做什么錯誤?
預期輸出,
3
4
5
輸出得到,
3
5
我的代碼,
var input1, input2;
input1 = Number(2);
input2 = Number(5);
for(let i=input1;i<input2;i ) {
i=i 1;
console.log(i);
}
uj5u.com熱心網友回復:
for 回圈已經i為您增加了。您撰寫的回圈在以下路徑中執行,從 1 -> 2 -> 3 -> 4 -> 2 -> 3 開始并重復,除非 3 處的檢查為假:
for(
let i=input1; // 1. Declare initial value [i]
i<input2; // 3. Check if [i] < [input2]
i // 4. increment [i] by 1
)
{
i=i 1; // 2. Run the contents of the loop body
console.log(i);
}
這意味著
// First iteration
i = input1 // 1. i = Number(2);
i = i 1; // 2. i = 2 1;
console.log(i) // 2. console.log(3);
i < input2 ? // 3. Check if i is smaller than input2. End loop if not
i ; // 4. Increment i so i = 4
// Second iteration
i = i 1; // 2. i = 4 1;
console.log(i) // 2. console.log(5);
i < input2 ? // 3. Check if i is smaller than input2. End loop if not
// End loop since i < input2 is not true
uj5u.com熱心網友回復:
即使它已經為您完成了,您也在回圈i體內遞增。for
input1應該也是3。
利用:
var input1, input2;
input1 = Number(3);
input2 = Number(5);
for (let i = input1; i <= input2; i ) {
console.log(i);
}
uj5u.com熱心網友回復:
您將變數“i”增加兩次
- 在 for 回圈
for(let i=input1;i<input2;i ) {} - 內部 for 回圈
i=i 1;
所以你的變數 'i' 將增加 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/411445.html
標籤:
上一篇:請幫我更正C程式中的代碼
