我使用remix IDE。当我调用该函数获取编号时,得到了0:uint256 []:
如何更改它以返回动态数组的数字?
实用性^ 0.4.24;
contract dynamicarray {
uint public constant MaxNumber = 50;
uint[] numbers;
function randomnumber() public view returns (uint){
uint random = uint(sha3(block.timestamp)) % MaxNumber +1;
for(uint i = MaxNumber; i > numbers.length; i++){
numbers.push(random);
return random;
}
}
function getnumbers() public view returns(uint[]){
return numbers;
}
}
答案 0 :(得分:1)
该函数是view
,因此它不能修改状态。调用randomnumber()
将返回一个值,但不会更改numbers
数组。
从view
中删除randomnumber()
修饰符,它将在数组中添加一项。 (提早返回将防止循环重复。)
答案 1 :(得分:0)
尝试一下
pragma solidity ^0.4.24;
contract dynamicarray {
uint public constant MaxNumber = 50;
uint[] numbers;
function randomnumber() public returns (uint){
uint random = uint(keccak256(block.timestamp)) % MaxNumber +1;
for(uint i = MaxNumber; i > numbers.length; i++){
numbers.push(random);
return random;
}
}
function getnumbers() public view returns(uint[]){
return numbers;
}
}