【发布时间】:2021-06-22 08:01:10
【问题描述】:
有问题的程序将候选人姓名和选民选择作为输入,输出是获胜者或获胜者的姓名(如果 2 个或多个候选人之间存在平局)。 每当我尝试使用自己的输入时,它都可以正常工作,无论是单个赢家还是多个赢家。 但 check50 不同意。当我使用调试器时,它最后说的是分段错误,但我看不出代码中的错误在哪里。
我无法理解为什么 check50 坚持认为程序不完全正确。 问题所在的代码部分是:
void print_winner(void)
{
int c = 0;
int d[(candidate_count - 1)];
int e = 0;
for (int i = 1; i < candidate_count; i++)
{
if (candidates[c].votes < candidates[i].votes)
{
c = i;
}
else if (candidates[c].votes == candidates[i].votes)
{
d[e] = i;
e++;
}
}
printf("%s\n", candidates[c].name);
for(int i = 0; i < (e + 1); i++)
{
if(candidates[c].votes == candidates[(d[i])].votes)
{
printf("%s\n", candidates[d[i]].name);
}
}
return;
}
结果是:
:) plurality.c exists
:) plurality compiles
:) vote returns true when given name of first candidate
:) vote returns true when given name of middle candidate
:) vote returns true when given name of last candidate
:) vote returns false when given name of invalid candidate
:) vote produces correct counts when all votes are zero
:) vote produces correct counts after some have already voted
:) vote leaves vote counts unchanged when voting for invalid candidate
:) print_winner identifies Alice as winner of election
:) print_winner identifies Bob as winner of election
:) print_winner identifies Charlie as winner of election
:) print_winner prints multiple winners in case of tie
:( print_winner prints all names when all candidates are tied
print_winner function did not print all three winners of election
【问题讨论】:
-
不确定,但这个:
for(int i = 0; i < (e + 1); i++)看起来很奇怪。我希望i < e -
欢迎来到 SO。分段错误显然是一些不被认为是通过的情况。通常 check50 会提供有关测试数据的一些信息。至少对于其他任务。对于失败的测试用例,它显示了哪些额外信息?
-
可以容纳
candidate_count - 1条目的数组的目的是什么?你的循环中i的范围是多少? -
编辑问题以包含minimal reproducible example。如果您没有重现问题的示例输入,您可以将其省略,但至少提供一个其他人可以编译和执行的完整程序。
标签: c segmentation-fault cs50