Solidity - do...while迴圈



do...while迴圈類似於while迴圈,區別在於條件檢查發生在迴圈的末尾。這意味著即使條件為false,迴圈也至少會執行一次。

流程圖

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

Do While Loop

語法

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

輸出

0: string: 12
solidity_loops.htm
廣告
© . All rights reserved.