V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
helloworld2048
V2EX  ›  区块链

solidity 入门问题求解

  •  
  •   helloworld2048 · 2023-02-23 21:33:27 +08:00 · 964 次点击
    这是一个创建于 400 天前的主题,其中的信息可能已经有所发展或是发生改变。
    contract FunctionTypes{
    function insertSort(int[] memory arr) external returns(int[] memory){
    for(int i=1;i<int(arr.length);i++){
    int temp=arr[i];
    for(int j=i-1;j>=0;j--){
    if(arr[j]>=temp) arr[j+1]=arr[j];
    else {
    arr[j+1]=temp;
    }
    }
    }
    return arr;
    }
    }

    在每一行赋值的地方都会报类型错误。我个人的理解是我在参数和变量声明时都声明了类型,为什么还会有类型错误?(不会发图..大家见谅,代码就是简单的插排)
    TypeError: Type int256 is not implicitly convertible to expected type uint256.
    4 条回复    2023-02-24 13:44:57 +08:00
    gasonzhong1
        1
    gasonzhong1  
       2023-02-24 10:04:32 +08:00
    改成这样就好了
    contract FunctionTypes {
    function insertSort(uint256[] memory arr)
    external
    returns (uint256[] memory)
    {
    for (uint256 i = 1; i < uint256(arr.length); i++) {
    uint256 temp = arr[i];
    for (uint256 j = i - 1; j >= 0; j--) {
    if (arr[j] >= temp) arr[j + 1] = arr[j];
    else {
    arr[j + 1] = temp;
    }
    }
    }
    return arr;
    }
    }
    helloworld2048
        2
    helloworld2048  
    OP
       2023-02-24 10:51:32 +08:00
    @gasonzhong1 感谢 int 为什么不行呢?因为 j 为负数跳出循环时用 uint 会报错,需要再单独处理一下,所以我想用 int 会更方便一些
    pengjay
        3
    pengjay  
       2023-02-24 11:24:58 +08:00
    arr[i]里的 i 只能是 uint 吧
    helloworld2048
        4
    helloworld2048  
    OP
       2023-02-24 13:44:57 +08:00
    @pengjay 这样的 感谢~
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2867 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 13:49 · PVG 21:49 · LAX 06:49 · JFK 09:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.