"print_candidate" 函数不工作。是逻辑错误吗?

The "print_candidate" function isnt working. Is it a logical error?

这是多人投票程序的代码。问题是最后一个函数中的 for 循环无法正常工作。输出在这里:

$ 使复数

clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow plurality.c -lcrypt -lcs50 - lm -o 复数

~/pset3/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.hstdbool.h 获取 false 定义。一定要-false吗,false不就够了吗?

  • for(int i=0;i<MAX;i++)

candidate candidates[MAX];是全局声明的,所以未初始化的元素默认为0。如果您的 candidate_count 小于 MAX 那么 strcmp(name,candidates[i].name) returns SIGSEGV 如果您尝试访问索引为 >= 到 [=24 的任何结构=] 并且你的程序崩溃了。应该是 for (int i = 0; i < candidate_count; i++).

  • if(strcmp(name,candidates[i].name))

如果 namecandidates[i].name 的字符串值相等,则 strcmp() returns 0,您可能需要此 if (strcmp(name, candidates[i].name) == 0).