Solidity - while 迴圈



Solidity 中最基本的迴圈是while迴圈,本章將對此進行討論。while迴圈的目的是隻要表示式為真,就重複執行語句或程式碼塊。一旦表示式變為,迴圈就會終止。

流程圖

while 迴圈的流程圖如下所示:

While loop

語法

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 第一個應用章節中提供的步驟執行以上程式。

輸出

0: string: 12
solidity_loops.htm
廣告

© . All rights reserved.