我刚刚完成对我的多个cs50程序的编程。它运行得很顺利,但当我检查时,它说它没有打印获胜者的名字,但它确实打印了。这是密码,有人能帮我吗?正如我所说,函数print_winner()
起作用,如果我运行debug50
,我可以看到这一点。通过命令行参数,我假设声明不超过9个候选人,选择我想要的票数,投票给候选人,然后程序假设宣布获胜者。问题是它做到了,但根据bot50的说法,它没有做到。
#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 < 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 n = candidate_count;
typedef struct
{
string name;
int votes;
}
bubble;
bubble bubbles[n];
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{ //doing a bubble sort to move the max vote at the end and doing
the same with the candidate name
if (candidates[i].votes > candidates[j].votes)
{
bubbles[0].votes = candidates[i].votes;
candidates[i].votes = candidates[j].votes;
candidates[j].votes = bubbles[0].votes;
bubbles[0].name = candidates[i].name;
candidates[i].name = candidates[j].name;
candidates[j].name = bubbles[0].name;
}
}
}
for (int i = 1; i <= n; i++)
{
if (candidates[n - i].votes == candidates[n - 1].votes)
{
printf("%s ", candidates[n - i].name);
}
printf("n");
}
}
如果能看到更多的代码,比如candidates
和candidate_count
是在哪里定义/初始化的,例如,如果你正在执行#include <string>
,这表明你实际上是using
std::string
,而不是其他版本的字符串。
如果是这样的话,那么std::string
的使用就很奇怪了。通常,strcmp()
需要一个指针,指向C样式的字符数组或类型const char*
。。。printf()
也是如此。。。所以你应该在name
和candidates[n - i].name
的用法后面加上.c_str()
。
即strcmp(candidates[i].name.c_str(), name.c_str())
和printf("%s ", candidates[n - i].name.c_str());
不过,再次假设您实际使用的是std::string
。