【发布时间】:2020-11-09 20:29:39
【问题描述】:
对于这个问题,我需要将人们输入的姓名与选票相匹配,然后将其计为一票。
There is a structure called candidate and I am trying to create an array of this structure to act as the ballot.代码如下:
typedef struct
{
string name;
int votes;
}
candidate;
// Array of candidates
candidate candidates[MAX];
candidates.name[0] = "Sam";
candidates.votes[0] = 0;
candidates.name[1] = "Stan";
candidates.votes[1] = 0;
candidates.name[2] = "Sara";
candidates.votes[2] = 0;
当我编译代码时,会弹出一个错误,提示缺少说明符,但之前已在结构中定义。
我查看了解决此问题的其他代码示例,但人们没有执行此步骤,因此可能没有必要,但即便如此我也不确定为什么。
这是其余的代码。
#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];
candidates[0].name = "Sam";
candidates[0].votes = 0;
candidates[1].name= "Stan";
candidates[1].votes = 0;
candidates[2].name = "Sara";
candidates[2].votes = 0;
// 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
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
// TODO
return;
}
【问题讨论】:
-
赋值表达式语句
candidates[0].name = "Sam";等语句需要在函数体内。不过,您不需要该代码,因为您从命令行参数中填写了main中的名称 -
在第一个示例中,您使用
candidates.name[0] = "Sam";,在第二个(完整)代码中使用candidates[0].name = "Sam";。现在您尝试编译的代码是什么?哪一行代码会弹出哪个错误? -
string是什么? -
@P__J__
char *-cs50.h标头的别名。 -
其他人可能没有执行此步骤,因为规范说“除了投票和 print_winner 函数的实现之外,您不应修改 multiple.c 中的任何其他内容”