c - “print_candidate”功能不起作用。这是逻辑错误吗?
问题描述
这是多个投票程序的代码。问题是最后一个函数中的 for 循环不能正常工作。输出在这里:
$ 使复数
clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow multiple.c -lcrypt -lcs50 -lm -o multiple
~/pset3/plurality/ $ ./plurality Alice Bob
选民人数:3
投票:爱丽丝
投票:鲍勃
投票:爱丽丝
鲍勃投票: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(int);
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)==-false)
{
printf("Invalid vote.\n");
}
}
// Display winner of election
print_winner(candidate_count);
}
// Update vote totals given a new vote
bool vote(string name)
{
int check=0;
for(int i=0;i<MAX;i++)
{
if(strcmp(name,candidates[i].name))
{
candidates[i].votes++;
break;
}
else
check++;
}
// TODO
if(check!=9)
{
return true;
}
return false;
}
// Print the winner (or winners) of the election
void print_winner(int ccount)
{
int i=0;
int count=0;
for (int j=0;j<ccount;j++)
{
if(i<candidates[j].votes)
{
i=candidates[j].votes;
count = j;
}
}
// TODO
printf("%s votes: %i \n", candidates[count].name,i);
return;
}
解决方案
从您的代码中,我可以很容易地看到以下错误:
if (vote(name)==-false)
cs50.h
从获取false
定义stdbool.h
。有没有必要-false
,false
不够?
for(int i=0;i<MAX;i++)
candidate candidates[MAX];
是全局声明的,因此未初始化元素的默认值为0
. 如果您candidate_count
的小于,那么如果您尝试访问其索引为的任何结构并且您的程序崩溃,MAX
则strcmp(name,candidates[i].name)
返回。应该是。SIGSEGV
>=
canditate_count
for (int i = 0; i < candidate_count; i++)
if(strcmp(name,candidates[i].name))
name
如果和的字符串值candidates[i].name
相等则strcmp()
返回0
,你可能想要这个if (strcmp(name, candidates[i].name) == 0)
。
推荐阅读
- mysql - 如何使用 MYSQL 选择不在列表中的值
- android - Android Studio IDE - 设计编辑器中不显示任何元素
- ios - 如何在不询问 iOS Swift 登录的情况下自动登录?
- jquery - 要在文本框中输入金额,值会自动转换为成本格式吗?
- avplayer - 关于 KVO key path operationCount 的 AVPlayerLayer 崩溃
- apple-push-notifications - 使用 http2 的 Apns 推送主题
- php - 为什么我在 Laravel 中收到此错误?
- node.js - 通过 safe-Url 使用 NodeJS 客户端 API 查询数据存储实体
- asp.net - Asp MVC 模型实体验证不显示必需的错误
- capybara - Capybara + RSpec + rbenv + Gitlab Runner: Selenium::WebDriver::Error::WebDriverError: 无法连接到 chromedriver 127.0.0.1:9515