c - 为什么没有打印出最多选票的“候选人”?
问题描述
bool print_winner(void)
{
int others = 0;
for (int i = 0; i < candidate_count; i++)
{
int h = others < candidate_count;
if(candidates[i].votes > candidates[h].votes
{
printf("%s\n", candidates[i].name);
return true;
}
}
return false;
} ``
candidates
来自这个结构:typedef struct { string name; int votes; bool eliminated; }
候选人;
我想要在函数中做的是打印得票最多(多数)的候选人的姓名。但是,当我编译程序时,什么都不会打印。 我还创建了这个函数来“消除”候选人,所以错误可能来自那里:
void tabulate(void)
{
int others = 0;
for(int i = 0; i<candidate_count; i++)
{
int h = others < candidate_count;
if(candidates[i].votes < candidates[h].votes)
{
//eliminate candidates[i].votes
candidates[i].eliminated = true;
}
}
return;
}
*当我编译我的程序时,似乎没有任何问题。
解决方案
您需要循环所有候选人并保留获胜者的数组索引例如
void print_winner(void)
{
int winner = 0;
if (!candidate_count)
return;
for (int i = 1; i < candidate_count; i++)
{
if(candidates[i].votes > candidates[winner].votes) {
winner = i;
}
}
printf("The winner is %s\n", candidates[winner].name);
}
推荐阅读
- javascript - 为什么我的控制器中的变量为空?
- javascript - Making commands case insensitive [Discord bot] in JS
- javascript - Vim Prettier 插件导致以 .js 扩展名结尾的文件出现错误
- javascript - 将带值的参数传递给函数不能按预期工作
- android - ViewModel 更新屏幕旋转
- python - 数据流作业停止随机处理数据
- python - 根据其他单元格的内容将数据添加到列(Python/Excel)
- angular - 函数记忆应该总是首选吗?
- c - 编译 C 文件时出错。致命错误:找不到“conio.h”文件
- django - 为什么我的表单中的输入没有写入 django 中的 sqlite3 数据库