c - 在 C 语言中,为什么这个函数在满足返回 true 的条件时返回 false?
问题描述
#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。当我翻转真假返回时,程序工作。这对我来说毫无意义,我正处于思考的边缘,我无法以一种我可以成功编码任何东西的方式思考。感谢您花时间阅读本文,如果有人这样做的话。
解决方案
您在这里没有正确阅读名称:
for (int i = 0; i < candidate_count; i++)
{
candidates[i].name = argv[i] + 1;
candidates[i].votes = 0;
}
这是从第二个字符开始获取每个字符串,从包含程序名称的参数开始。
你放+1
错地方了。你想要的是:
candidates[i].name = argv[i + 1];
推荐阅读
- ios - 同一个视图控制器出现两次
- android - 如何将加载栏添加到视图位于另一个活动中的适配器类
- bash - 通过匹配 iptables 和 netstat 的脚本检查打开的 WAN 端口?
- angular - 如何将字符串参数转换为变量 TypeScript Angular 的属性
- python - 无法在python中获取反转的字符串
- django - 调用 CreateMultipartUpload 操作时发生错误 (SignatureDoesNotMatch):
- c# - 如何从窗口服务内部在浏览器中加载网页
- c# - 提交表单时无法获取外键值
- javascript - 角度 7 响应解析器无法正常工作
- windows - 如何在 WSL 中编译面向 64 位 Windows 的 GCC 9.1