V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
helloworld2048
V2EX  ›  区块链

solidity 入门问题求解

  •  
  •   helloworld2048 · Feb 23, 2023 · 2207 views
    This topic created in 1165 days ago, the information mentioned may be changed or developed.
    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 replies    2023-02-24 13:44:57 +08:00
    gasonzhong1
        1
    gasonzhong1  
       Feb 24, 2023
    改成这样就好了
    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
       Feb 24, 2023
    @gasonzhong1 感谢 int 为什么不行呢?因为 j 为负数跳出循环时用 uint 会报错,需要再单独处理一下,所以我想用 int 会更方便一些
    pengjay
        3
    pengjay  
       Feb 24, 2023
    arr[i]里的 i 只能是 uint 吧
    helloworld2048
        4
    helloworld2048  
    OP
       Feb 24, 2023
    @pengjay 这样的 感谢~
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1195 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 17:10 · PVG 01:10 · LAX 10:10 · JFK 13:10
    ♥ Do have faith in what you're doing.