代码适用于小数字,但由于某种原因,当我输入大数字并启动程序时,然后写一个名称2次,第一次程序添加一个,但第二次程序没有添加任何内容并告诉我“无效名称”,而对于大数字,当我开始写其他名称时,它会给我“分段错误(核心转储)”。
#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 largest(int list[], int n);
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
vote(name);
if (strcmp(name, candidates[i].name) != 0)
{
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(NAME, candidates[i].name) == 0)
{
candidates[i].votes++;
}
}
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
int Votes_here[candidate_count];
for (int j = 0; j < candidate_count; j++)
{
Votes_here[j] = candidates[j].votes;
}
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes == largest(Votes_here, candidate_count))
{
printf("%s\n", candidates[i].name);
}
}
return;
}
int largest(int list[], int n)
{
int i;
int l = list[0];
for (i = 1; i < n; i++)
{
if (list[i] > l)
l = list[i];
}
return l;
}
我期待着该程序计算选票,并返回谁拥有最多的选票赢家
1条答案
按热度按时间zbdgwd5y1#
问题是,您使用的变量
i
将选民计数作为candidates
数组的索引。如果投票者比候选人多,您将访问数组外部。即使你不去数组外,strcmp(name, candidates[i].name) != 0
的比较也是没有意义的--为什么第i个投票者要投票给第i个候选人?vote()
函数应该返回一个指示符,指示是否找到了候选对象。然后,您可以在if
语句中检查这一点。