c-CS50 pset3复数:当给定无效候选人时,为什么投票函数不返回false



根据check50,当给定无效候选人的名称时,投票函数不会返回false。此外,当投票给无效候选人时,它会修改总票数。我按照指示保留了主要功能。请帮忙!我在这里没看到什么?

编辑:添加了其余代码。当我以Alice和Bob为候选人,并试图投票给Steve,而不是";无效投票";正如输出应该是的那样;分段故障";。

#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Max number of candidates
#define MAX 9
// Candidates have name and vote count
typedef struct
{
string name;
int votes;
}
candidate;
// Array of candidates
candidate candidates[MAX];
// Number of candidates
int candidate_count;
// Function prototypes
bool vote(string name);
void print_winner(void);
int main(int argc, string argv[])
{
// Check for invalid usage
if (argc < 2)
{
printf("Usage: plurality [candidate ...]n");
return 1;
}
// Populate array of candidates
candidate_count = argc - 1;
if (candidate_count > MAX)
{
printf("Maximum number of candidates is %in", MAX);
return 2;
}
for (int i = 0; i < candidate_count; i++)
{
candidates[i].name = argv[i + 1];
candidates[i].votes = 0;
}
int voter_count = get_int("Number of voters: ");
// Loop over all voters
for (int i = 0; i < voter_count; i++)
{
string name = get_string("Vote: ");
// Check for invalid vote
if (!vote(name))
{
printf("Invalid vote.n");
}
}
// Display winner of election
print_winner();
}
// Update vote totals given a new vote
bool vote(string name)
{
for (int i = 0; i < MAX; i++)
{
if (strcmp(candidates[i].name, name) == 0)
{
candidates[i].votes++;
return true;
}
}
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
int high = 0;
for (int i = 0; i < MAX; i++)
{
if (candidates[i].votes > high)
{
high = candidates[i].votes;
}
}
for (int j = 0; j < MAX; j++)
{
if (candidates[j].votes == high)
{
printf("%sn", candidates[j].name);
}
}
return;
}

在vote和print_winner中,您在整个候选数组上循环。

for (int i = 0; i < MAX; i++)

当您只填写2个候选者并试图访问尚未初始化的数组的第三项时,您认为会发生什么?通常是未定义的行为。

相关内容

最新更新