Solidity - While 循环


Solidity 中最基本的循环是本章将讨论的while循环。while循环的目的是只要表达式为就重复执行语句或代码块。一旦表达式变为假,循环就会终止。

流程图

while 循环的流程图如下 -

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 Application章节中提供的步骤运行上述程序。

输出

0: string: 12
Solidity_loops.htm