首页 > 解决方案 > “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;
}

标签: ccs50

解决方案


从您的代码中,我可以很容易地看到以下错误:

  • if (vote(name)==-false)

cs50.h从获取false定义stdbool.h。有没有必要-falsefalse不够?

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

candidate candidates[MAX];是全局声明的,因此未初始化元素的默认值为0. 如果您candidate_count的小于,那么如果您尝试访问其索引为的任何结构并且您的程序崩溃,MAXstrcmp(name,candidates[i].name)返回。应该是。SIGSEGV>=canditate_countfor (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)


推荐阅读