首页 > 解决方案 > CS50 径流 - 为什么我的代码中的“strcmp() 函数”实际上有效?

问题描述

虽然我已经成功完成了练习的投票功能部分,但bool vote(int voter, int rank, string name)我并没有真正看到计算机是如何通过代码行的: if (strcmp(candidates[i].name, name) == 0)在下面的投票功能中是正确的。

例如,假设您输入 3 个候选项作为argv's。"dim", "oli" & "mat"按照这个顺序。选民 0在 的部分中选择'mat dim oli'作为他的偏好。// Keep querying for votesint main

那怎么可能if (strcmp(candidates[i].name, name) == 0)是正确的呢?

因为在第一个循环中,i = 0,candidates[i].name等于"dim"( argv [0 + 1]),但第一个选民选择"mat"了他的第一偏好(排名 0),实际上是 ( ) 与( )argv [2 + 1]不匹配,不是吗?"dim"argv [0 + 1]

也许在这种情况下逐步解释循环如何工作会有所帮助。

// preferences[i][j] is jth preference for voter i
int preferences[MAX_VOTERS][MAX_CANDIDATES];

// Candidates have name, vote count, eliminated status
typedef struct
{
    string name;
    int votes;
    bool eliminated;
}
candidate;

// Array of candidates
candidate candidates[MAX_CANDIDATES];

// Numbers of voters and candidates
int voter_count;
int candidate_count;

// Function prototypes
bool vote(int voter, int rank, string name);


int main(int argc, string argv[])
{
 
    // Populate array of candidates
    candidate_count = argc - 1;
    
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
        candidates[i].eliminated = false;
    }

    voter_count = get_int("Number of voters: ");
    
    // Keep querying for votes
    for (int i = 0; i < voter_count; i++)
    {
        // Query for each rank
        for (int j = 0; j < candidate_count; j++)
        {
            string name = get_string("Rank %i: ", j + 1);

            // Record vote, unless it's invalid
            if (!vote(i, j, name))
            {
                printf("Invalid vote.\n");
                return 4;
            }
        }
        printf("\n");
    }

// Record preference if vote is valid
bool vote(int voter, int rank, string name)
{
    // TODO
    for (int i = 0; i < candidate_count; i++)
    {
        **if (strcmp(candidates[i].name, name) == 0)**
        {
        preferences[voter][rank] = i;
        return true;
        }
    }
    return false;
}

标签: ccs50

解决方案


strcmp的返回值视为“差异”,其中 0 表示“没有差异”,或者换句话说,匹配。如果您曾经被难住,那么您的第一站应该是文档,因为这就是我们所有人了解事情应该如何工作的方式。

换句话说strcmp("dim","dim")将是0


推荐阅读