[英]CS50 pset3 Plurality: why does vote function not return false when given invalid candidate?
[英]What does return 2 mean in C? And additional questions on bool and void. CS50 Pset 3 Plurality
目前正在进行 CS50 Pset3 复数练习并查看给出的代码。 我想知道代码中的 return 2 是什么意思。
一些额外的问题 -
为什么是布尔投票(字符串名称); 和 void print_winner(void); 不在 int main (int argc, string arg[]) 的大括号内? 我不确定为什么要这样写,我想了解这背后的原因。
#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 < candidate_count; i++)
{
if (strcmp(candidates[i].name, name) == 0)
{
candidates[i].votes++;
return true;
}
}
// TODO
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
int maxvote = 0;
for (int i = 0; i < candidate_count; i++)
{
if (maxvote < candidates[i].votes)
{
maxvote = candidates[i].votes;
}
}
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes == maxvote)
{
printf("%s\n", candidates[i].name);
}
}
// TODO
return;
}
在main()
中return 2
function 表示程序将以退出代码 2 退出,表示错误(任何非零值通常都被视为错误)。 程序设置如下:
main()
结束时缺少return 0
)返回代码在程序中没有意义。 但是,当程序实际运行时,父进程(通常是 shell,例如 Bash)可以解释返回代码以收集有关进程状态的有意义的信息。
这些
bool vote(string name);
void print_winner(void);
是 function 声明,允许在它们之后编写的代码调用具有给定签名的函数。 定义在代码后面; 在 C 中,function 定义不需要与声明在同一个文件中,只要在链接时可以找到 function 即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.