【发布时间】:2021-08-22 16:46:58
【问题描述】:
我一直在做 CS50 第 3 周的多元问题集,我看到了非常奇怪的输出。这是我的代码。
#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)
{
// TODO
for (int i = 0; i < candidate_count; i++)
{
if (strcmp(candidates[i].name, name) == 0)
{
candidates[i].votes = candidates[i].votes + 1;
return true;
}
}
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
string winner[candidate_count];
int max_vote = 0;
int current_index = 0;
for (int i = 0; i < candidate_count; i++)
{
if (i == 0)
{
max_vote = candidates[i].votes;
winner[current_index] = candidates[i].name;
current_index++;
}
else if (i > 0)
{
if (candidates[i].votes > max_vote)
{
for (int j = 0; j < candidate_count; j++)
{
winner[j] = "0";
}
current_index = 0;
winner[current_index] = candidates[i].name;
current_index++;
max_vote = candidates[i].votes;
}
else if (candidates[i].votes == max_vote)
{
winner[current_index] = candidates[i].name;
current_index++;
}
}
}
for (int k = 0; k < current_index + 1; k++)
{
if (strcmp(winner[k], "0") != 0)
{
printf("Hello %s\n", winner[k]);
}
}
}
我像这样运行代码-
~/pset3/plurality/ $ ./plurality Alice Bob Kyaw Soe
Number of voters: 2
Vote: Alice
Vote: Bob
预期的输出是 -
~/pset3/plurality/ $ ./plurality Alice Bob Kyaw Soe
Number of voters: 2
Vote: Alice
Vote: Bob
Hello Alice
Hello Bob
但实际结果是-
~/pset3/plurality/ $ ./plurality Alice Bob Kyaw Soe
Number of voters: 2
Vote: Alice
Vote: Bob
Hello Alice
Hello Bob
Hello AWL=#(
我的问题是 AWL=#( 是什么意思?如果我使用 Bob 和 Kyaw 而不是 Alice,我得到了我的预期结果。“Alice”在内部对这个问题做了什么?有人可以吗?请解释一下?
【问题讨论】:
-
我建议您学习如何使用 调试器,以及如何使用它来逐句执行代码,同时监控变量及其值。
-
请停止使用'string'来隐藏'char*'
-
@tstanisl 是的,但它是 CS50 课程的一部分。
-
for (int k = 0; k < current_index + 1; k++)应该是for (int k = 0; k < current_index; k++)