【问题标题】:CS50 pset3 Plurality: why does vote function not return false when given invalid candidate?CS50 pset3 复数:为什么给定无效候选人时投票功能不返回 false?
【发布时间】:2021-07-11 14:02:54
【问题描述】:

根据 check50,当给定一个无效候选人的名字时,投票函数不会返回 false。此外,它会在投票给无效候选人时修改总票数。根据说明,我保持主要功能不变。请帮忙!我在这里没有看到什么?

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

#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;
}

【问题讨论】:

  • 请发帖minimal reproducible example,包括您的输入和输出。单独的功能没有问题。
  • @EugeneSh。你认为是什么导致了这个分段错误?据我了解,它发生在尝试访问数组外部的内存时。我仍然不明白这是怎么发生的,因为 i 在 for 循环中应该保持小于 MAX
  • 你不应该迭代到MAX,你应该迭代到实际的候选人数量。你迭代的任何地方。
  • 所以你需要将candidate_count 传递给遍历数组的所有函数。
  • 知道了,谢谢!

标签: c cs50


【解决方案1】:

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

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

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

【讨论】:

  • 当然!谢谢!我忘了候选人的数量是由输入给出的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
  • 2020-12-02
  • 1970-01-01
  • 2016-09-05
相关资源
最近更新 更多