【发布时间】:2020-07-30 12:09:01
【问题描述】:
以下代码通过选举中的每个选民,并允许他们按偏好对候选人进行排名:1、2、3 等。
代码有效,但我只是想了解将一个 int 分配给ints、preferences[voter][rank] = i 的二维数组时会发生什么。
将单个 int 分配给 ints 的二维数组时会发生什么?
// Keep querying for votes
for (int i = 0; i < voter_count; i++)
{
// Query for each rank
for (int j = 0; j < candidate_count; j++)
{
string name = get_string("Rank %i: ", j + 1);
// Record vote, unless it's invalid
if (!vote(i, j, name))
{
printf("Invalid vote.\n");
return 4;
}
}
printf("\n");
}
//first loop through ranks gets input from the user... this loop through compares the users
//response to each of the candidates, then locks them in as that rank for that voter
bool vote(int voter, int rank, string name)
{
for (int i = 0; i < candidate_count; i++)
{
if(strcmp(name, candidates[i].name) == 0)
{
preferences[voter][rank] = i;
return true;
}
}
return false;
}
【问题讨论】:
标签: arrays c multidimensional-array