区块链学堂(20):Int类型

Int类型官方介绍

int / uint: Signed and unsigned integers of various sizes. Keywords uint8 to uint256 in steps of 8 (unsigned of 8 up to 256 bits) and int8 to int256. uint and int are aliases for uint256 and int256, respectively. 引用自here

int & uint

int代表有符号的整型,也就是可以带负数
uint代表没有符号的整型,也就是从0开始的正整数

uint8 代表为2的8次方
uint256 代表为2的256次方
uint 默认为 uint256

int8 代表为-2的7次方到正2的7次方
int256 代表为-2的255次方,到正2的255次方;
int 默认为int256

整型操作符

comparisons: <=, <, ==, !=, >=, >

bit operator: &, |, ^,~

arithmetic operator: +, -, *, /, %, **, <<, >>

几个整型的实际代码

最简单的整型合约,f(n) = 8 * n;
pragma solidity ^0.4.4;
contract DemoTypes {
  function f(uint a) returns (uint b)
  {
    uint result = a * 8;
    return result;
  }
}
输入width & height,返回两者相乘的智能合约,加入了if命令
contract DemoTypes {
  function f2(int width, int height) returns (int square) {
    if (width < 0 || height < 0) throw;
    int result = width * height;
    return result;
  }
}
输入N,用For循环来计算阶乘数
contract DemoTypes {
  /*输入N,计算N的阶乘,循环实现*/
  function f3(uint n) returns (uint jiecheng) {
    if (n == 0) throw; uint result = 1;
    for (uint i=1; i<=n; i++) {
      result *= i;
    }
    return result;
  }
}
输入N,用For循环来计算1+2+3+..+N求和。
contract DemoTypes {
  /*计算从1到N的求和*/
  function f4(uint n) returns (uint sum) {
    if (n == 0) throw; uint result = 0;
    for (uint i=0; i<=n; i++) {
      result +=i;
    }
    return result;
  }
}

在合约中写入测试代码

  • 区块链的技术和以前的技术最大的不同就在于开源化,尤其是智能合约部分,必须要开源。因此测试代码就非常重要;
  • 所以建议大家在撰写智能合约到时候都能顺带把测试代码写上 这个也是成为以太坊开源社区贡献者的必备条件。

所以我们可以在上面的f4()方法的下方,添加一部分测试代码代码如下:

contract DemoTypes2 {
  uint public testResult;
  /*计算从1到N的求和*/
  function f4(uint n) returns (uint sum) {
    if (n == 0) throw; uint result = 0;
    for (uint i=0; i<=n; i++) {
      result +=i;
    }
    return result;
  }

  function g() {
    testResult = f4(3);
  }
}

增加了一个可观察的变量uint public testResult;, 然后在function g()中调用f4()方法,这个时候可以通过在browser-solidity中观察变量testResult即可。

  • 当然这个方法是费时费力的,以太坊的白皮书里面,没有提供在智能合约中的assert方法,因为更希望智能合约本身短小精悍,
  • 但在Truffle中我们可以轻松的使用测试框架来实现对智能合约的测试工作。在后面的章节中我们会具体来讲如何测试一个智能合约。

下一章节,我们将介绍最常用的string类型,敬请期待。

猜你喜欢

转载自blog.csdn.net/lala_wang/article/details/79752144