9.1 Solidity中的控制流
9.1.1 for循环
定义数组:
uint[] public a = [4,5,1,2,7,9,8,6,3];
for循环计算sum:
// sum: for循环
function forSum() external view returns (uint) {
uint sum = 0;
for(uint i = 0;i < a.length;i++) {
sum += a[i];
}
return sum;
}
循环中的控制语句break和continue和大部分语言相同,不再赘述。
9.1.2 while循环
while循环计算sum:
// sum:while循环
function whileSum() external view returns (uint) {
uint sum = 0;
uint i = 0;
while (i < a.length){
sum += a[i];
i ++;
}
return sum;
}
9.1.3 do-while循环
do-while循环计算sum:
// sum:do-while循环
function doWhileSum() external view returns (uint) {
uint sum = 0;
uint i = 0;
do {
sum += a[i];
i++;
}while (i < a.length);
return sum;
}
9.1.4 if-else
// if-else
function ifElseTest(uint _number) public pure returns(bool){
if(_number == 0){
return(true);
}else{
return(false);
}
}
9.1.5 三元运算符
// 三元运算
function sanTest(uint _number) public pure returns(bool){
return _number == 0 ? true : false;
}
网友评论