我正在尝试处理投票功能,有两个问题想寻求您的帮助:
bool vote(int rank, string name, int ranks[])
我不明白rank参数的用途,为什么在这里声明它?
// Update ranks given a new vote
bool vote(int rank, string name, int ranks[])
{
for (int j = 0; j < candidate_count; j++)
{
for (int k = 0; k < candidate_count; k++)
{
//Compare the name provided by the user with the name of the candidates numbered jth in the array candidates[MAX] which already populated above
if (strcmp(name, candidates[k]) == 0)
{
ranks[j] = k;
printf("ranks[%d] = %d\n", j, k);
}
}
return true;
}
return false;
}
printf函数的结果如下(候选数= {a,b,c},voter_count = 2):
等级1:a,等级[0] = 0;等级2:b,等级[0] = 1;等级3:c,等级[0] = 2;等级1:c,等级[0] = 2;等级2:b,等级[0] = 1;等级3:a,等级[0] = 0
等级[j]中j的值未更新。我该如何解决这个问题?
非常感谢你的帮助!
这是一些代码:
// Update ranks given a new vote
bool vote(int rank, string name, int ranks[]){
//We want to cycle through the list of candidates given
for(int i = 0; i < candidate_count; i++){
//If the candidate(s) in the array matches with string name, we will continue
if(strcmp(candidates[i], name) == 0){
//This is the tricky part to understand. Read below for answer.
ranks[rank] = i;
return true;
}
}
return false;
}
int rank
代表用户在候选人中的给定排名,并且int i
代表候选人在中的位置candidates[]
。我们要ranks[]
根据正确的排名进行更新。仍然很难理解,因此这里是一个示例。
我们有四个候选人:约翰,吉姆,山姆,亚历克斯
在
string candidates[MAX];
,约翰在candidates[0]
,吉姆在candidates[1]
,山姆在candidates[2]
,亚历克斯在candidates[3]
。
假设用户投票,并按以下顺序投票:
让我们在中运行它bool vote(int rank, string name, int ranks[])
。
vote(j, name, ranks)
其中j = 0,名称= Alex,ranks是ranks []- 我们将循环使用Alex的名称,直到在中找到它为止
candidates[MAX]
。candidates[i]
在i = 3的地方找到了Alex 。- 我们要更新
ranks[]
ranks[rank] = i;
表示atranks[rank]
等于i等于3。换句话说,ranks [0]等于Alex在中的第i个位置candidates[MAX]
。
然后重复此循环,直到完成所有选民的排名。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句