[英]CS50 pset3 Plurality: why does vote function not return false when given invalid candidate?
根據 check50,投票 function 在給出無效候選人的姓名時不會返回 false。 此外,它會在投票給無效候選人時修改總票數。 根據說明,我將主 function 保持不變。 請幫忙? 我在這里沒有看到什么?
編輯:添加了代碼的 rest。 當我以 Alice 和 Bob 作為候選人的示例運行它並嘗試投票給 Steve 時,而不是 output 應該的“無效投票”,它給了我“分段錯誤”。
#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 %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 < 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("%s\n", candidates[j].name);
}
}
return;
}
在 vote 和 print_winner 中,你循環整個候選數組。
for (int i = 0; i < MAX; i++)
當您僅填寫 2 個候選人並嘗試訪問尚未初始化的數組的第 3 項時,您認為會發生什么? 通常,未定義的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.