我一直在通过 CS50 来学习编码的基础知识。我成功地制作了多个问题集 3,但我真的不明白布尔值是如何工作的。所以具体问题是:
1) boolean 的结构如何工作?2) 何时以及如何调用它?
我试图了解使用它的基本方面。谢谢你的帮助。
这是代码:
#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)
{
// TODO
for (int i = 0; i < candidate_count; i++)
{
if (strcmp (name, candidates[i].name) == 0)
{
candidates[i].votes++;
return true;
}
}
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
// TODO
for (int i = 1; i < candidate_count; i++)
{
if (candidates[0].votes < candidates[i].votes)
candidates[0].votes = candidates[i].votes;
}
printf ("%s\n", candidates[0].name);
for (int i = 1; i < candidate_count; i++)
{
if (candidates[0].votes == candidates[i].votes)
printf ("%s\n", candidates[i].name);
}
return;
}
Run Code Online (Sandbox Code Playgroud)
在这段代码中如何调用 bool ?
您对此处的术语有一些重大误解。询问“ bool 如何被调用”没有任何意义。让我为你澄清一些:
bool就是我们所说的“数据类型”。其他数据类型是int和char。这些定义了内存中值的含义。例如,int是正负整数,char是字母和符号,bool是真还是假。
函数是我们“调用”的东西。更具体地说,函数是执行特定任务的一段代码。我们“调用”该函数以使其执行该任务。这就是为什么问“bool 何时被调用”是没有意义的。我们从不“调用 bool”,因为bool它是数据类型而不是函数。
当我们声明一个函数时,我们必须提供 3 条信息:函数名称、输入列表(或更准确地说是每个输入的类型)和函数结果的类型(称为“返回值”)类型”)。编写时bool vote(string name);,这会声明一个名为的函数,该函数vote将 astring作为输入并返回 a bool。
混淆可能是因为我们将其bool用作函数定义的一部分。在上面的例子中,我们只是说调用vote()函数的结果是真或假。
考虑到所有这些,我们可以讨论何时vote()调用该函数。要弄清楚这一点,您只需查看所有出现的单词的代码vote。如果你这样做,你会发现一行if (!vote(name))。这vote()就是所谓的。换句话说,我们告诉计算机执行vote()函数中的代码,它返回一个真值或假值,用于评估 if 语句的条件。
当你继续学习编程时,一定要密切关注术语。像许多其他学科一样,我们有自己的词汇。为了与其他程序员交流,您需要使用正确的词语。更重要的是,理解我们使用的词将帮助您更清楚地理解概念,以便您可以自己应用它们。