Solidity 练习:循环语句

2022-12-29 Web3 Solidity

# 一、题目说明

看一下下边的 for 和 While 循环的例子。

// for 循环
for (uint i = 0; i < 10; i++) {
    if (i == 3) {
        // continue 跳到下一个循环
        continue;
    }
    if (i == 5) {
        // break 退出循环
        break;
    }
}

// while 循环
uint j;
while (j < 10) {
    j++;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 二、任务列表

  • 完成函数 sum。
  • 这个函数应该返回从 1 到 _n 所有数字的和(包括 _n)。
  • 例如:sum(5) 应该返回 1 + 2 + 3 + 4 + 5 = 15。

# 三、解答代码

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

contract ForAndWhileLoops {
    function sum(uint _n) external pure returns (uint) {
        uint ans;
        for (uint i = 1; i <= _n; i++) {
            ans += i;
        }
        return ans;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12

# 四、参考资料

Last Updated: 2023-01-28 4:31:25