【以太坊入门】写一个简单的投票程序有一个不知道怎么解决的warning
本帖最后由 thepoy 于 2020-7-12 09:34 编辑代码如下:
```solidity
pragma solidity >=0.4.21;
contract Voting {
struct voter {
address voterAddress;
uint tokenNum;
uint[] tokensVoteForCandidates;
}
uint public totalTokens;
uint public tokenBalance;
uint public tokenPrice;
bytes32[] public candidateList;
mapping(bytes32=>uint) public votesReceived;
mapping(address=>voter) public voterInfo;
constructor(uint totalSupply, uint price, bytes32[] memory candidateNames) public {
totalTokens = totalSupply;
tokenBalance = totalSupply;
tokenPrice = price;
candidateList = candidateNames;
}
function voteForCandidate(bytes32 candidate, uint voteTokens) public {
uint index = indexOfCandidate(candidate);
require(index!=uint(-1));
if(voterInfo.tokensVoteForCandidates.length==0){
for (uint i = 0; i < candidateList.length; i++){
voterInfo.tokensVoteForCandidates.push(0);
}
}
uint availableTokens = voterInfo.tokenNum - totalUsedTokens(voterInfo.tokensVoteForCandidates);
require(availableTokens>=voteTokens);
votesReceived += voteTokens;
voterInfo.tokensVoteForCandidates += voteTokens;
}
function indexOfCandidate(bytes32 candidate) public view returns(uint){
for (uint i = 0; i < candidateList.length; i++){// warning在这里:i++无法达到
if(candidate==candidateList){
return i;
}
return uint(-1);
}
}
}
```
写的时候就有注意到这个warning,但想到warning嘛,又不是error,就没管它,没想到部署合约后无法正常动行,经排查就是这个warning的原因。
在用indexOfCandidate查找指定candidate时,candidateList里只有一个元素,但constructor初始化时,给candidateList赋值的是有3个元素的bytes32[],但在indexOfCandidate里的candidateList却只有第一个元素,所以无法取到其他元素,所以导致整个程序运行错误。
请问我该如何调整修改代码,能够使indexOfCandidate里的candidateList是我初始化的candidateList?
return uint(-1);在循环体外,没注意到 缩进很重要,但自动缩进(代码格式化)更重要
有一个大括号没有闭合,导致直接return uint(-1)进而引发警告. 最近数字是不是也很火?
页:
[1]