【发布时间】:2020-07-03 03:34:35
【问题描述】:
我试图了解为什么在 CS50 的复数(第 3 周)中使用候选计数而不是选民计数。下面是我的代码。
如果我们假设我们有 3 个候选人(Alice、Bob、Charlie),并且每次我们迭代 bool 函数或 print_winner 函数时,如果我们有 10 个选民,我们会不会错过计票?根据我的理解,“我”只会迭代 3 次。我在理解为什么我们不会在底部的打印获胜者函数中使用 voter_count 时遇到一个概念问题。
我仍在尝试改进我的代码,所以部分可能仍然存在错误。我只是在寻求一些帮助来澄清这个问题的逻辑。
#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 (number of arguments - 1 because the first arg is going to be plurality)
candidate_count = argc - 1;
if (candidate_count > MAX)
{
printf("Maximum number of candidates is %i\n", 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 < candidate_count; 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 maxvotes = 0;
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes > maxvotes)
{
maxvotes = candidates[i].votes;
}
}
for (int i = 0; i < candidate_count; i++)
{
printf("the winner is %s\n!", candidates[i].name);
}
return;
}
【问题讨论】:
标签: cs50