Solidity - do...while 循环
do...while 循环与 while 循环类似,只是条件检查发生在循环末尾。 这意味着即使条件为 false,循环也将始终至少执行一次。
流程图
do-while循环的流程图如下 −
语法
Solidity中do-while循环的语法如下 −
do {
Statement(s) to be executed;
} while (expression);
注意 − 不要错过 do...while 循环末尾使用的分号。
示例
尝试以下示例来了解如何在 Solidity 中实现 do-while 循环。
pragma solidity ^0.5.0;
contract SolidityTest {
uint storedData;
constructor() public{
storedData = 10;
}
function getResult() public view returns(string memory){
uint a = 10;
uint b = 2;
uint result = a + b;
return integerToString(result);
}
function integerToString(uint _i) internal pure
returns (string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
do { // do while loop
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
while (_i != 0);
return string(bstr);
}
}
使用 Solidity First 应用 章节中提供的步骤运行上述程序。
输出
0: string: 12

