Solidity - While 循环
Solidity 中最基本的循环是本章将讨论的 while 循环。 while 循环的目的是,只要表达式 为真,就重复执行语句或代码块。 一旦表达式变为 false, 循环就会终止。
流程图
while 循环的流程图如下 −

语法
Solidity中while 循环的语法如下 −
while (expression) { Statement(s) to be executed if expression is true }
示例
尝试以下示例来实现 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; while (_i != 0) { // while loop bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } }
使用 Solidity First 应用 章节中提供的步骤运行上述程序。
输出
0: string: 12