【问题标题】:In C, why does this function return false when conditions are met for it to return true?在 C 中,为什么这个函数在满足返回 true 的条件时返回 false?
【发布时间】:2021-04-22 09:49:27
【问题描述】:
#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。当我翻转真假返回时,程序工作。这对我来说毫无意义,我正处于思考的边缘,我无法以一种我可以成功编码任何东西的方式思考。感谢您花时间阅读本文,如果有人这样做的话。

【问题讨论】:

  • 什么是get_string?它是否将用户的输入作为分配的字符串返回?它是否包含尾随换行符?输入是否与预期字符串之一完全匹配
  • @jamesdlin 它是 cs50 库的一部分。已添加标签。
  • 好的,所以它显然是某个库的一部分,请回答@jamesdlin 的其他问题。它返回什么?

标签: c function printing boolean cs50


【解决方案1】:

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

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

【讨论】:

  • 这就是我阅读代码时的想法,但是投票功能上方的所有内容都提供给了我,因此不需要更改程序即可正常运行。我完全注意到你指出的内容,但我按照课程的说明进行操作。如果这就是问题所在,我会很生气,我在这个大声笑上浪费了这么多的生命。
猜你喜欢
  • 1970-01-01
  • 2018-11-09
  • 2018-08-27
  • 1970-01-01
  • 2021-01-15
  • 2021-05-03
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多