Solidity do…while 循环

1. 语法

Solidity 中, do…while循环的语法如下:

do {
   // 如果表达式的结果为真,就循环执行以下语句
   ......
} while (表达式);

2. 示例

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SolidityTest {
   uint storedData; 
   constructor() {
      storedData = 10;   
   }
   function getResult() public pure 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 循环 
         bstr[k--] = byte(uint8(48 + _i % 10));
         _i /= 10;
      }
      while (_i != 0);
      return string(bstr);
   }
}

运行上述程序,输出结果:

0: string: 12

下一章:Solidity for 循环

 1. 语法Solidity 中, for循环的语法如下:for (初始化; 测试条件; 迭代语句) { // 如果表达式的结果为真,就循环执行以下语句 ......} 2. 示例// S ...