c - 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 votes
int 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;
}
解决方案
将strcmp
的返回值视为“差异”,其中 0 表示“没有差异”,或者换句话说,匹配。如果您曾经被难住,那么您的第一站应该是文档,因为这就是我们所有人了解事情应该如何工作的方式。
换句话说strcmp("dim","dim")
将是0
。
推荐阅读
- python - 运行此代码后,它为两个骰子吐出相同的值,我怎样才能将随机值固定为每次都不同?
- android - 用 bottomNavigationView 后按
- c++ - PPM 错误颜色显示
- csv - Weka - 第 X 行的问题......将 csv 转换为 ARFF
- powerbi - 您可以从不相关的切片器更新 DAX 函数吗?
- java - 数据库更改日志表未在 Liquibase 的 Postgres 环境中创建
- ssl - OpenSSL TLS服务器无法获取客户端证书
- python-3.x - Altair 为交互式散点图添加日期滑块
- android - Android Kotlin:以字节码显示图像
- c# - C# LDAP DirectoryEntry 查询根条目