【发布时间】:2021-04-22 09:49:27
【问题描述】:
#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 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)
{
//variable index
int x;
//loop through candidate names to find a match with the input name, add a ballot if there is a
match
for (x = 0; x < candidate_count; x++)
{
if (strcmp(candidates[x].name, name) == 0)
{
candidates[x].votes++;
return true;
}
}
return false;
}
此代码通过函数投票查看用户输入字符串是否与参数字符串匹配。我不明白为什么它一直打印“无效投票”,就好像在给出正确的名称时函数返回 false,并且函数应该返回 true。当我翻转真假返回时,程序工作。这对我来说毫无意义,我正处于思考的边缘,我无法以一种我可以成功编码任何东西的方式思考。感谢您花时间阅读本文,如果有人这样做的话。
【问题讨论】:
-
什么是
get_string?它是否将用户的输入作为分配的字符串返回?它是否包含尾随换行符?输入是否与预期字符串之一完全匹配? -
@jamesdlin 它是 cs50 库的一部分。已添加标签。
-
好的,所以它显然是某个库的一部分,请回答@jamesdlin 的其他问题。它返回什么?
标签: c function printing boolean cs50