solidity 入门问题求解

2023-02-23 21:33:27 +08:00
 helloworld2048
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.
1018 次点击
所在节点    区块链
4 条回复
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
2023-02-24 10:51:32 +08:00
@gasonzhong1 感谢 int 为什么不行呢?因为 j 为负数跳出循环时用 uint 会报错,需要再单独处理一下,所以我想用 int 会更方便一些
pengjay
2023-02-24 11:24:58 +08:00
arr[i]里的 i 只能是 uint 吧
helloworld2048
2023-02-24 13:44:57 +08:00
@pengjay 这样的 感谢~

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/918665

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX