Update iteration code.

This commit is contained in:
krahets
2023-08-25 02:22:57 +08:00
parent 3e64f68ae9
commit ae304bd605
4 changed files with 15 additions and 14 deletions

View File

@@ -23,7 +23,7 @@ int whileLoop(int n) {
// 循环求和 1, 2, ..., n-1, n
while (i <= n) {
res += i;
i += 1; // 更新条件变量
i++; // 更新条件变量
}
return res;
}
@@ -32,12 +32,12 @@ int whileLoop(int n) {
int whileLoopII(int n) {
int res = 0;
int i = 1; // 初始化条件变量
// 循环求和 1, 2, 4, 5...
// 循环求和 1, 4, ...
while (i <= n) {
res += i;
i += 1; // 更新条件变量
res += i;
i *= 2; // 更新条件变量
// 更新条件变量
i++;
i *= 2;
}
return res;
}

View File

@@ -24,7 +24,7 @@ public class iteration {
// 循环求和 1, 2, ..., n-1, n
while (i <= n) {
res += i;
i += 1; // 更新条件变量
i++; // 更新条件变量
}
return res;
}
@@ -33,12 +33,12 @@ public class iteration {
public static int whileLoopII(int n) {
int res = 0;
int i = 1; // 初始化条件变量
// 循环求和 1, 2, 4, 5...
// 循环求和 1, 4, ...
while (i <= n) {
res += i;
i += 1; // 更新条件变量
res += i;
i *= 2; // 更新条件变量
// 更新条件变量
i++;
i *= 2;
}
return res;
}

View File

@@ -29,12 +29,12 @@ def while_loop_ii(n: int) -> int:
"""while 循环(两次更新)"""
res = 0
i = 1 # 初始化条件变量
# 循环求和 1, 2, 4, 5...
# 循环求和 1, 4, ...
while i <= n:
res += i
i += 1 # 更新条件变量
res += i
i *= 2 # 更新条件变量
# 更新条件变量
i += 1
i *= 2
return res