繁体   English   中英

CS50 pset3 复数:为什么在给定无效候选人时投票 function 不返回 false?

[英]CS50 pset3 Plurality: why does vote function not return false when given invalid candidate?

根据 check50,投票 function 在给出无效候选人的姓名时不会返回 false。 此外,它会在投票给无效候选人时修改总票数。 根据说明,我将主 function 保持不变。 请帮忙? 我在这里没有看到什么?

编辑:添加了代码的 rest。 当我以 Alice 和 Bob 作为候选人的示例运行它并尝试投票给 Steve 时,而不是 output 应该的“无效投票”,它给了我“分段错误”。

#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)
{
    for (int i = 0; i < MAX; i++)
    {
        if (strcmp(candidates[i].name, name) == 0)
        {
            candidates[i].votes++;
            return true;
        }
    }
    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    int high = 0;
    for (int i = 0; i < MAX; i++)
    {
        if (candidates[i].votes > high)
        {
            high = candidates[i].votes;
        }
    }
    for (int j = 0; j < MAX; j++)
    {
        if (candidates[j].votes == high)
        {
            printf("%s\n", candidates[j].name);
        }
    }
    return;
}

在 vote 和 print_winner 中,你循环整个候选数组。

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

当您仅填写 2 个候选人并尝试访问尚未初始化的数组的第 3 项时,您认为会发生什么? 通常,未定义的行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM