首页 > 解决方案 > 在 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。当我翻转真假返回时,程序工作。这对我来说毫无意义,我正处于思考的边缘,我无法以一种我可以成功编码任何东西的方式思考。感谢您花时间阅读本文,如果有人这样做的话。

标签: cfunctionprintingbooleancs50

解决方案


您在这里没有正确阅读名称:

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];

推荐阅读