这是用户在 2024-9-18 23:23 为 https://cs50.harvard.edu/x/2024/notes/1/ 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?

Lecture 1 第一讲

Welcome! 欢迎您!

  • In our previous session, we learned about Scratch, a visual programming language.
    在我们之前的课程中,我们学习了 Scratch,这是一种可视化编程语言。
  • Indeed, all the essential programming concepts presented in Scratch will be utilized as you learn how to program any programming language.
    学习如何编程任何编程语言时,Scratch 中展示的所有基本编程概念都将被运用。
  • Recall that machines only understand binary. Where humans write source code, a list of instructions for the computer that is human readable, machines only understand what we can now call machine code. This machine code is a pattern of ones and zeros that produces a desired effect.
    请记住,机器只能理解二进制代码。人类编写源代码,这是一种人类可读的计算机指令集,而机器只能理解我们现在称之为机器代码的东西。这种机器代码是由一系列 0 和 1 组成的模式,它会产生预期的效果。
  • It turns out that we can convert source code into machine code using a very special piece of software called a compiler. Today, we will be introducing you to a compiler that will allow you to convert source code in the programming language C into machine code.
    事实证明,我们可以利用一种非常特殊的软件,称为编译器,将源代码转换为 machine code 。今天,我们将向您介绍一个编译器,它可以帮助您将 C 语言的源代码转换为机器代码。
  • Today, in addition to learning about how to code, you will be learning about how to write good code.
    今天,除了学习编程技巧外,你还将学习如何编写高质量的代码。
  • Code can be evaluated upon three axes. First, correctness refers to “does the code run as intended?” Second, design refers to “how well is the code designed?” Finally, style refers to “how aesthetically pleasing and consistent is the code?”
    代码评估可以从三个方面进行。首先,正确性是指“代码是否按预期运行?”其次,设计是指“代码的设计水平如何?”最后,风格则是指“代码在美观性和一致性上表现如何?”

Hello World 您好,世界

  • The integrated development environment (IDE) that is utilized for this course is Visual Studio Code, affectionately referred to as , which can be accessed via that same url, or simply as *VS Code.*
    本课程使用的集成开发环境(IDE)是 Visual Studio Code,亲切地称为 VS Code,可以通过同一网址访问。
  • One of the most important reasons we utilize VS Code is that it has all the software required for the course already pre-loaded on it. This course and the instructions herein were designed with VS Code in mind.
    我们使用 VS Code 的一个重要原因是它已经预装了本课程所需的所有软件。这个课程及其说明都是专门为 VS Code 设计的。
  • Manually installing the necessary software for the course on your own computer is a cumbersome headache. Best always to utilize VS Code for assignments in this course.
    在自己的电脑上手动安装课程所需的软件非常麻烦。最好始终使用 VS Code 来完成本课程的作业。
  • You can open VS Code at cs50.dev.
    你可以在 cs50.dev 网站上打开 VS Code。
  • The compiler can be divided into a number of regions:
    编译器可以划分为多个区域:

    IDE Notice that there is a file explorer on the left side where you can find your files. Further, notice that there is a region in the middle called a text editor where you can edit your program. Finally, there is a command line interface, known as a CLI, command line, or terminal window where we can send commands to the computer in the cloud.
    请注意,左侧有一个文件浏览器,您可以在其中找到您的文件。此外,中间有一个区域称为文本编辑器,您可以在这里编辑您的程序。最后,还有一个 command line interface ,称为 CLI、命令行或终端窗口,您可以通过它向云端计算机发送命令。

  • We will be using three commands to write, compile, and run our first program:
    我们将使用三个命令来编写、编译和运行我们的第一个程序

    code hello.c
    
    make hello
    
    ./hello
    
    

    The first command, code hello.c creates a file and allows us to type instructions for this program. The second command, make hello, compiles the file from our instructions in C and creates an executable file called hello. The last command, ./hello, runs the program called hello.
    第一个命令, code hello.c 用于创建一个文件,并允许我们为此程序输入指令。第二个命令, make hello ,会根据我们的 C 语言指令编译文件,并生成一个名为 hello 的可执行文件。最后一个命令, ./hello 会运行名为 hello 的程序。

  • We can build your first program in C by typing code hello.c into the terminal window. Notice that we deliberately lowercased the entire filename and included the .c extension. Then, in the text editor that appears, write code as follows:
    我们可以通过在终端窗口中输入 code hello.c 来创建您的第一个 C 程序。请注意,我们特意将完整的文件名小写,并添加了 .c 扩展名。接下来,在打开的文本编辑器中,按如下方式编写代码:

    #include <stdio.h>
    
    int main(void)
    {
        printf("hello, world\n");
    }
    

    Note that every single character above serves a purpose. If you type it incorrectly, the program will not run. printf is a function that can output a line of text. Notice the placement of the quotes and the semicolon. Further, notice that the \n creates a new line after the words hello, world.
    请注意,上述每个字符都有其特定用途。如果输入错误,程序将无法运行。 printf 是一个可以输出一行文本的函数。请注意引号和分号的位置。此外, \nhello, world 之后会生成一个新行。

  • Clicking back in the terminal window, you can compile your code by executing make hello. Notice that we are omitting .c. make is a compiler that will look for our hello.c file and turn it into a program called hello. If executing this command results in no errors, you can proceed. If not, double-check your code to ensure it matches the above.
    在终端窗口中点击后退按钮,您可以通过执行 make hello 来编译代码。请注意,我们省略了 .cmake 是一个编译器,它会查找我们的 hello.c 文件,并将其转换成名为 hello 的程序。如果执行命令没有错误,您可以继续。如果没有,请仔细检查您的代码,确保它与上面的代码一致。
  • Now, type ./hello and your program will execute saying hello, world.
    现在输入 ./hello ,你的程序将执行并输出 hello, world
  • Now, open the file explorer on the left. You will notice that there is now both a file called hello.c and another file called hello. hello.c is able to be read by the compiler: It’s where your code is stored. hello is an executable file that you can run, but cannot be read by the compiler.
    现在,打开左侧的文件资源管理器。你会发现,这里有两个文件:一个是名为 hello.c 的文件,另一个名为 hello 的文件。 hello.c 是可以被编译器读取的,它存储着你的代码。 hello 是一个可执行文件,你可以运行它,但编译器无法读取它。

Functions 功能

  • In Scratch, we utilized the say block to display any text on the screen. Indeed, in C, we have a function called printf that does exactly this.
    在 Scratch 中,我们使用 say 块在屏幕上显示任何文本。实际上,在 C 语言中,我们有一个名为 printf 的函数,就能完成这个功能。
  • Notice our code already invokes this function:
    请注意,我们的代码已经调用了这个函数:

    printf("hello, world\n");
    

    Notice that the printf function is called. The argument passed to printf is ‘hello, world\n’. The statement of code is closed with a ;.
    请注意,printf 函数被调用。传递给 printf 的参数是‘hello, world\n’。这条代码语句以 ; 结束。

  • A common error in C programming is the omission of a semicolon. Modify your code as follows:
    C 编程中常见的错误是忘记写分号。 请按如下方式修改您的代码:

    #include <stdio.h>
    
    int main(void)
    {
        printf("hello, world\n")
    }
    

    Notice the semicolon is now gone.
    请注意,分号现在已经去掉了。

  • In your terminal window, run make hello. You will now be met with numerous errors! Placing the semicolon back in the correct position and running make hello again, the errors go away.
    在您的终端窗口中运行 make hello 。您会遇到很多错误!将分号放回正确的位置,然后再次运行 make hello ,错误就会消失。
  • Notice also the special symbol \n in your code. Try removing those characters and making your program again by executing make hello. Typing ./hello in the terminal window, how did your program change? This \ character is called an escape character that tells the compiler that \n is a special instruction.
    请注意你代码中的特殊符号 \n 。 尝试删除这些字符,然后通过执行 make hello 重新创建你的程序。 在终端窗口中输入 ./hello ,看看你的程序发生了什么变化? 这个 \ 字符被称为转义字符,它告诉编译器 \n 代表一个特殊指令。
  • Restore your program to the following:
    请将您的程序恢复到以下状态:

    #include <stdio.h>
    
    int main(void)
    {
        printf("hello, world\n");
    }
    

    Notice the semicolon and \n have been restored.
    请注意,分号和 \n 已恢复。

  • The statement at the start of the code #include <stdio.h> is a very special command that tells the compile that you want to use the capabilities of a library called stdio.h, a header file. This allows you, among many other things, to utilize the printf function. You can read about all the capabilities of this library on the Manual Pages. The Manual Pages provide a means by which to better understand what various commands do and how they function.
    代码 #include <stdio.h> 开头的语句是一个非常特殊的命令,它告诉编译器你希望使用一个名为 stdio.h 的库的功能,这个库是一个头文件。这样,你就可以在许多其他情况下使用 printf 函数。你可以在手册页面上查看该库的所有功能,手册页面提供了一种更好理解各种命令及其功能的方式。
  • Libraries are collections of pre-written functions that others have written in the past that we can utilize in our code.
    库是由其他人过去编写的预先写好的函数的集合,我们可以在自己的代码中加以利用。
  • It turns out that CS50 has its own library called cs50.h. Let’s use this library in your program.
    结果显示,CS50 有一个名为 cs50.h 的库。让我们在你的程序中使用这个库。

Variables 变量名称

  • Recall that in Scratch, we had the ability to ask the user “What’s your name?” and say “hello” with that name appended to it.
    还记得在 Scratch 中,我们可以向用户提问“你叫什么名字?”,然后用他们的名字加上“你好”来回答。
  • In C, we can do the same. Modify your code as follows:
    在 C 语言中,我们可以采取相同的方式。请修改你的代码如下:

    #include <stdio.h>
    
    int main(void)
    {
        string answer = get_string("What's your name? ");
        printf("hello, %s\n", answer);
    }
    

    The get_string function is used to get a string from the user. Then, the variable answer is passed to the printf function. %s tells the printf function to prepare itself to receive a string.
    使用 get_string 函数从用户获取字符串,并将变量 answer 传递给 printf 函数。 %s 指示 printf 函数准备接收一个 string

  • answer is a special holding place we call a variable. answer is of type string and can hold any string within it. There are many data types, such as int, bool, char, and many others.
    answer 是一个我们称之为变量的特殊占位符。 answer 的数据类型是 string ,可以存储任何字符串。还有许多其他数据类型,例如 intboolchar 等等。
  • %s is a placeholder called a format code that tells the printf function to prepare to receive a string. answer is the string being passed to %s.
    %s 是一个占位符,称为格式代码,它告诉 printf 函数准备接收一个 stringanswer 是传递给 %sstring
  • Running make hello again in the terminal window, notice that numerous errors appear.
    在终端窗口中再次运行 make hello 时,请注意会出现很多错误。
  • Looking at the errors string and get_string are not recognized by the compiler. We have to teach the compiler these features by adding a library called cs50.h:
    查看错误 stringget_string ,编译器无法识别。我们需要通过添加名为 cs50.h 的库来教编译器识别这些功能:

    #include <cs50.h>
    #include <stdio.h>
    
    int main(void)
    {
        string answer = get_string("What's your name? ");
        printf("hello, %s\n", answer);
    }
    

    Notice that #include <cs50.h> has been added to the top of your code.
    请注意, #include <cs50.h> 已经添加到了您的代码顶部。

  • Now running make hello again in the terminal window, you can run your program by typing ./hello. The program now asks for your name and then says hello with your name attached, as intended.
    现在在终端窗口中再次运行 make hello ,您可以通过输入 ./hello 来运行您的程序。程序会询问您的名字,然后以您的名字进行问候,正如预期的那样。
  • printf allows for many format codes. Here is a noncomprehensive list of ones you may utilize in this course:
    printf 支持多种格式代码。以下是你在本课程中可以使用的一些常见格式代码:

    %c
    
    %f
    
    %i
    
    %li
    
    %s
    

    %s is used for string variables. %i is used for int or integer variables. You can find out more about this on the Manual Pages
    %s 用于 string 变量, %i 则用于 int 或整数变量。你可以在手册页中找到更多信息。

Conditionals 条件语句

  • Another building block you utilized within Scratch was that of conditionals. For example, you might want to do one thing if x is greater than y. Further, you might want to do something else if that condition is not met.
    在 Scratch 中,你使用的另一个构建块是条件判断。例如,如果 x 大于 y,你可能想要执行某个操作;而如果这个条件不满足,你可能需要执行另一种操作。
  • We look at a few examples from Scratch.
    我们来看几个 Scratch 的例子。
  • In C, you can assign a value to an int or integer as follows:
    在 C 语言中,您可以通过以下方式为 int 或整数赋值:

    int counter = 0;
    

    Notice how a variable called counter of type int is assigned the value 0.
    注意如何将一个类型为 int 、名为 counter 的变量赋值为 0

  • C can also be programmed to add one to counter as follows:
    C 语言也可以编程实现将 counter 加一,具体方法如下:

    counter = counter + 1;
    

    Notice how 1 is added to the value of counter.
    注意 1 如何添加到 counter 的值。

  • This can be represented also as:
    这也可以表示成:

    counter = counter++;
    

    Notice how 1 is added to the value of counter. However the ++ is used instead of counter + 1.
    请注意 1 如何添加到 counter 的值。但是,使用了 ++ 而不是 counter + 1

  • You can also subtract one from counter as follows:
    你也可以从 counter 中减去 1,方法如下:

    counter = counter--;
    

    Notice how 1 is removed to the value of counter.
    注意 1 如何被移除到 counter 的值。

  • Using this new knowledge about how to assign values to variables, you can program your first conditional statement.
    通过掌握如何为变量赋值的新知识,你可以编写你的第一个条件语句。
  • In the terminal window, type code compare.c and write code as follows:
    在终端窗口中,输入 code compare.c 并按照以下方式编写代码:

    #include <cs50.h>
    #include <stdio.h>
    
    int main(void)
    {
        int x = get_int("What's x? ");
        int y = get_int("What's y? ");
    
        if (x < y)
        {
            printf("x is less than y\n");
        }
    }
    

    Notice that we create two variables, an int or integer called x and another called y. The values of these are populated using the get_int function.
    请注意,我们创建了两个变量,一个是名为 x 的整数 int ,另一个是名为 y 的变量。这些值是通过 get_int 函数来填充的。

  • You can run your code by executing make compare in the terminal window, followed by ./compare. If you get any error messages, check your code for errors.
    您可以通过在终端窗口中执行 make compare ,然后执行 ./compare 来运行代码。如果出现错误消息,请检查代码是否存在问题。
  • Flow charts are a way by which you can examine how a computer program functions. Such charts can be used to examine the efficiency of our code.
    流程图是一种用于分析计算机程序功能的方法。这些图表可以帮助我们评估代码的效率。
  • Looking at a flow chart of the above code, we can notice numerous shortcomings.
    从以上代码的流程图来看,我们可以发现许多缺陷。
  • We can improve your program by coding as follows:
    我们可以通过以下方法来提升您的程序:

    #include <cs50.h>
    #include <stdio.h>
    
    int main(void)
    {
        int x = get_int("What's x? ");
        int y = get_int("What's y? ");
    
        if (x < y)
        {
            printf("x is less than y\n");
        }
        else if (x > y)
        {
            printf("x is greater than y\n");
        }
        else
        {
            printf("x is equal to y\n");
        }
    }
    

    Notice that all potential outcomes are now accounted for.
    请注意,现在所有潜在结果都已被考虑在内。

  • You can re-make and re-run your program and test it out.
    你可以重新创建并运行你的程序,进行测试。
  • Examining this program on a flow chart, you can see the efficiency of our code design decisions.
    通过查看这个程序的流程图,你可以了解到我们代码设计决策的效率。
  • Considering another data type called a char we can start a new program by typing code agree.c into the terminal window.
    考虑到一种名为 char 的数据类型,我们可以通过在终端窗口中输入 code agree.c 来启动一个新程序。
  • Where a string is a series of characters, a char is a single character.
    其中 string 表示一系列字符, char 表示单个字符。
  • In the text editor, write code as follows:
    在文本编辑器中,请按如下方式编写代码:

    #include <cs50.h>
    #include <stdio.h>
    
    int main(void)
    {
        // Prompt user to agree
        char c = get_char("Do you agree? ");
    
        // Check whether agreed
        if (c == 'Y' || c == 'y')
        {
            printf("Agreed.\n");
        }
        else if (c == 'N' || c == 'n')
        {
            printf("Not agreed.\n");
        }
    }
    

    Notice that single quotes are utilized for single characters. Further, notice that == ensure that something is equal to something else, where a single equal sign would have a very different function in C. Finally, notice that || effectively means or.
    请注意,单引号用于表示单个字符。此外, == 用于确保某个值等于另一个值,而在 C 语言中,单个等号的功能则截然不同。最后, || 实际上表示“或”。

  • You can test your code by typing make agree into the terminal window, followed by ./agree.
    你可以在终端窗口中输入 make agree ,接着输入 ./agree 来测试你的代码。

Loops 循环结构

  • We can also utilize the loops building block from Scratch in our C programs.
    我们也可以在 C 程序中利用 Scratch 的循环模块。
  • We look at a few examples from Scratch. Consider the following code:
    我们来看几个来自 Scratch 的例子。请看下面的代码:

    int counter = 3;
    while (counter > 0)
    {
        printf("meow\n");
        counter = counter - 1;
    }
    

    Notice that his code assigns the value of 3 to the counter variable. Then, the while loop says meow and removes one from the counter for each iteration. Once the counter is not greater than zero, the loop ends.
    他的代码将 3 的值赋给 counter 变量。然后, while 循环执行 meow 操作,并每次迭代将计数器减 1。当计数器不再大于零时,循环结束。

  • In your terminal window, type code meow.c and write code as follows:
    在您的终端窗口中,输入 code meow.c ,然后编写以下代码:

    #include <stdio.h>
    
    int main(void)
    {
        printf("meow\n");
        printf("meow\n");
        printf("meow\n");
    }
    

    Notice this does as intended but has an opportunity for better design.
    虽然这已经实现了预期功能,但设计上还有提升空间。

  • We can improve our program by modifying your code as follows:
    我们可以通过以下方式修改您的代码,从而改进我们的程序:

    #include <stdio.h>
    
    int main(void)
    {
        int i = 3;
        while (i > 0)
        {
            printf("meow\n");
            i--;
        }
    }
    

    Notice that we create an int called i and assign it the value 3. Then, we create a while loop that will run as long as i > 0. Then, the loop runs. Every time 1 is subtracted to i using the i-- statement.
    注意我们创建了一个名为 iint ,并将其赋值为 3 。然后,我们创建了一个 while 循环,它会一直运行到 i > 0 。循环开始运行后,每次使用 i-- 语句将 1i 中减去。

  • Similarly, we can implement a count-up of sorts by modifying our code as follows:
    同样地,我们可以通过修改代码来实现类似计数的功能

    #include <stdio.h>
    
    int main(void)
    {
        int i = 1;
        while (i <= 3)
        {
            printf("meow\n");
            i++;
        }
    }
    

    Notice how our counter i is started at 1. Each time the loop runs, it will increment the counter by 1. Once the counter is greater than 3, it will stop the loop.
    请注意,我们的计数器 i1 开始。每次循环运行时,计数器会增加 1 。一旦计数器的值超过 3 ,循环将停止。

  • Generally, in computer science we count from zero. Best to revise your code as follows:
    一般来说,在计算机科学中,我们是从零开始计数的。建议您按以下方式修改代码:

    #include <stdio.h>
    
    int main(void)
    {
        int i = 0;
        while (i < 3)
        {
            printf("meow\n");
            i++;
        }
    }
    

    Notice we now count from zero.
    请注意,我们现在从零开始计数。

  • Another tool in our toolbox for looping is a for loop.
    我们工具箱中用于循环的另一种工具是 for 循环。
  • You can further improve the design of our meow.c program using a for loop. Modify your code as follows:
    你可以使用一个 for 循环来进一步改进我们 meow.c 程序的设计。请按照以下方式修改你的代码:

    #include <stdio.h>
    
    int main(void)
    {
        for (int i = 0; i < 3; i++)
        {
            printf("meow\n");
        }
    }
    

    Notice that the for loop includes three arguments. The first argument int i = 0 starts our counter at zero. The second argument i < 3 is the condition that is being checked. Finally, the argument i++ tells the loop to increment by one each time the loop runs.
    请注意, for 循环包含三个参数。第一个参数 int i = 0 将计数器初始化为零。第二个参数 i < 3 是被检查的条件。最后,参数 i++ 指示循环每次运行时自增 1。

  • We can even loop forever using the following code:
    我们甚至可以利用以下代码实现无限循环:

    #include <cs50.h>
    #include <stdio.h>
    
    int main(void)
    {
        while (true)
        {
            printf("meow\n");
        }
    }
    

    Notice that true will always be the case. Therefore, the code will always run. You will lose control of your terminal window by running this code. You can break from an infinite by hitting control-C on your keyboard.
    请注意, true 始终成立。因此,代码会一直执行。运行此代码时,您将失去对终端窗口的控制。您可以通过在键盘上按下 control-C 来中断无限循环。

  • While we will provide much more guidance later, you can create your own function within C as follows:
    尽管我们稍后会提供更多指导,但你可以按照以下方式在 C 语言中创建自己的函数:

    void meow(void)
    {
        printf("meow\n");
    }
    

    The initial void means that the function does not return any values. The (void) means that no values are being provided to the function.
    初始 void 表示这个函数不返回任何值,而 (void) 则意味着没有向函数提供任何值。

  • This function can be used in the main function as follows:
    在主函数中,您可以像这样使用此函数:

    #include <stdio.h>
    
    void meow(void);
    
    int main(void)
    {
        for (int i = 0; i < 3; i++)
        {
            meow();
        }
    }
    
    void meow(void)
    {
        printf("meow\n");
    }
    

    Notice how the meow function is called with the meow() instruction. This is possible because the meow function is defined at the bottom of the code and the prototype of the function is provided at the top of the code as void meow(void).
    注意 meow 函数是如何使用 meow() 指令调用的。这是因为 meow 函数在代码底部定义,并且函数的原型在代码顶部以 void meow(void) 的形式声明。

  • Your meow function can be further modified to accept input:
    您的 meow 函数可以进一步修改,使其能够接受输入

    #include <stdio.h>
    
    void meow(int n);
    
    int main(void)
    {
        meow(3);
    }
    
    // Meow some number of times
    void meow(int n)
    {
        for (int i = 0; i < n; i++)
        {
            printf("meow\n");
        }
    }
    

    Notice that the prototype has changed to void meow(int n) to show that meow accepts an int as its input.
    请注意,原型已更改为 void meow(int n) ,以表明 meow 接受 int 作为输入。

Operators and Abstraction
运算符与抽象

  • You can implement a calculator in C. In your terminal, type code calculator.c and write code as follows:
    你可以用 C 语言实现一个计算器。在终端中输入 code calculator.c ,然后按照以下代码编写:

    #include <cs50.h>
    #include <stdio.h>
    
    int main(void)
    {
        // Prompt user for x
        int x = get_int("x: ");
    
        // Prompt user for y
        int y = get_int("y: ");
    
        // Perform addition
        printf("%i\n", x + y);
    }
    

    Notice how the get_int function is utilized to obtain an integer from the user twice. One integer is stored in the int variable called x. Another is stored in the int variable called y. Then, the printf function prints the value of x + y, designated by the %i symbol.
    注意如何两次使用 get_int 函数从用户获取整数。一个整数存储在名为 xint 变量中,另一个存储在名为 yint 变量中。接着, printf 函数打印由 %i 符号指定的 x + y 的值。

  • Operators refer to the mathematical operations that are supported by your compiler. In C, these mathematical operators include:
    操作符指的是您的编译器支持的数学运算。在 C 语言中,这些数学运算符包括:

    • + for addition  + 用于加法运算
    • - for subtraction  - 用于减法运算
    • * for multiplication 使用 * 进行乘法运算
    • / for division  / 用于除法运算
    • % for remainder  % 用于计算余数
  • Abstraction is the art of simplifying our code such that it deals with smaller and smaller problems.
    抽象是一种将代码简化的艺术,使其能够处理越来越小的、更具体的问题。
  • Expanding on our previously acquired knowledge about functions, we could abstract away the addition into a function. Modify your code as follows:
    在已有的关于函数知识的基础上,我们可以将加法抽象成一个函数。请按照以下方式修改您的代码:

    #include <cs50.h>
    #include <stdio.h>
    
    int add(int a, int b);
    
    int main(void)
    {
        // Prompt user for x
        int x = get_int("x: ");
    
        // Prompt user for y
        int y = get_int("y: ");
    
        // Perform addition
        int z = add(x, y);
        printf("%i\n", z);
    }
    
    int add(int a, int b)
    {
        int c = a + b;
        return c;
    }
    

    Notice that the add function takes two variables as its input. These values are assigned to a and b and preforms a calculation, returning the value of c. Further, notice that the scope (or context in which variables exist) of x is the main function. The variable c is only within the scope of the add function.
    请注意, add 函数接收两个变量作为输入,分别赋值给 ab ,并进行计算,最终返回 c 的值。此外, x 的作用域(或变量存在的上下文)位于 main 函数中。变量 c 仅在 add 函数的作用域内有效。

  • The design of this program can be further improved as follows:
    该程序的设计可以进一步改进,具体如下:

    #include <cs50.h>
    #include <stdio.h>
    
    int add(int a, int b);
    
    int main(void)
    {
        // Prompt user for x
        int x = get_int("x: ");
    
        // Prompt user for y
        int y = get_int("y: ");
    
        // Perform addition
        printf("%i\n", add(x, y));
    }
    
    int add(int a, int b)
    {
        return a + b;
    }
    

    Notice that c in the add function is removed entirely.
    请注意,在 add 函数中, c 已完全删除。

  • While very useful to be able to abstract away to an add function, you can also perform addition through truncation as follows:
    虽然将其抽象为一个 add 函数非常有用,但你也可以通过截断的方式进行加法,具体如下:

    #include <cs50.h>
    #include <stdio.h>
    
    int main(void)
    {
        // Prompt user for x
        long x = get_long("x: ");
    
        // Prompt user for y
        long y = get_long("y: ");
    
        // Perform addition
        printf("%li\n", x + y);
    }
    

    Notice that the addition is performed within the printf function.
    请注意,添加操作是在 printf 函数内进行的。

  • Similarly, division can be performed as follows:
    同样地,除法可以按照以下步骤进行:

    #include <cs50.h>
    #include <stdio.h>
    
    int main(void)
    {
        // Prompt user for x
        int x = get_int("x: ");
    
        // Prompt user for y
        int y = get_int("y: ");
    
        // Divide x by y
        printf("%i\n", x / y);
    }
    

    Notice that division is performed within the printf function.
    请注意,除法运算是在 printf 函数内部进行的。

Linux and the Command Line
Linux 与命令行工具

  • Linux is an operating system that is accessible via the command line in the terminal window in VS Code.
    Linux 是一个可以通过 VS Code 终端窗口中的命令行进行访问的操作系统。
  • Some common command-line arguments we may use include:
    我们常用的一些命令行参数包括:
    • cd, for changing our current directory (folder)
      cd ,用于更改当前目录(文件夹)
    • cp, for copying files and directories
      用于复制文件和文件夹
    • ls, for listing files in a directory
      列出目录中的文件
    • mkdir, for making a directory
      用于创建文件夹
    • mv, for moving (renaming) files and directories
      用于移动(重命名)文件和目录的 mv
    • rm, for removing (deleting) files
      用于删除文件的 rm
    • rmdir, for removing (deleting) directories
      rmdir ,用于删除目录
  • The most commonly used is ls which will list all the files in the current directory or directory. Go ahead and type ls into the terminal window and hit enter. You’ll see all the files in the current folder.
    最常用的命令是 ls ,它会列出当前目录或文件夹中的所有文件。请在终端窗口中输入 ls ,然后按下 enter 键。你将看到当前文件夹中的所有文件。
  • Another useful command is mv, where you can move a file from one file to another. For example, you could use this command to rename Hello.c (notice the uppercase H) to hello.c by typing mv Hello.c hello.c.
    另一个有用的命令是 mv ,它可以将文件从一个位置移动到另一个位置。例如,您可以使用此命令将 Hello.c (注意 H 大写)重命名为 hello.c ,方法是键入 mv Hello.c hello.c
  • You can also create folders. You can type mkdir pset1 to create a directory called pset1.
    你也可以创建文件夹。输入 mkdir pset1 可以创建一个名为 pset1 的目录。
  • You can then use cd pset1 to change your current directory to pset1.
    然后,你可以使用 cd pset1 将当前目录更改为 pset1

Mario 马里奥

  • Everything we’ve discussed today has focused on various building-blocks of your work as an emerging computer scientist.
    我们今天讨论的所有内容都围绕着您作为一名新兴计算机科学家所要进行的工作的各个组成部分。
  • The following will help you orient toward working on a problem set for this class in general: How does one approach a computer science related problem?
    以下内容将帮助你更好地了解如何处理本课程的问题集:应该如何解决与计算机科学相关的问题?
  • Imagine we wanted to emulate the visual of the game Super Mario Bros. Considering the four question-blocks pictured, how could we create code that roughly represents these four horizontal blocks?
    想象一下我们想要模拟《超级马里奥兄弟》游戏的视觉效果。考虑到这四个问号方块,我们该如何编写代码来大致表示这四个水平方块呢?

    Mario Question Marks

  • In the terminal window, type code mario.c and code as follows:
    在终端窗口中,输入 code mario.c 并按如下方式编写代码:

    #include <stdio.h>
    
    int main(void)
    {
        for (int i = 0; i < 4; i++)
        {
            printf("?");
        }
        printf("\n");
    }
    

    Notice how four question marks are printed here using a loop.
    请注意,这里使用循环打印出四个问号。

  • Similarly, we can apply this same logic to be able to create three vertical blocks.
    类似地,我们可以用相同的逻辑来创建三个垂直区域。

    Mario Blocks

  • To accomplish this, modify your code as follows:
    要做到这一点,请按照以下方式修改您的代码:

    #include <stdio.h>
    
    int main(void)
    {
        for (int i = 0; i < 3; i++)
        {
            printf("#\n");
        }
    }
    

    Notice how three vertical bricks are printed using a loop.
    请注意,循环是如何打印出三个垂直的砖块的。

  • What if we wanted to combine these ideas to create a three-by-three group of blocks?
    如果我们想把这些想法结合在一起,创建一个三乘三的方块组,该怎么做?

    Mario Grid

  • We can follow the logic above, combining the same ideas. Modify your code as follows:
    我们可以依照上述逻辑,结合相同的思路。请按以下方式修改您的代码:

    #include <stdio.h>
    
    int main(void)
    {
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                printf("#");
            }
            printf("\n");
        }
    }
    

    Notice that one loop is inside another. The first loop defines what vertical row is being printed. For each row, three columns are printed. After each row, a new line is printed.
    请注意,一个循环嵌套在另一个循环中。外层循环定义了要打印的垂直行。对于每一行,打印三个列。每打印完一行,就会换行。

  • What if we wanted to ensure that the number of blocks to be constant, that is, unchangeable? Modify your code as follows:
    如果我们想确保块的数量保持不变,即不可更改,请按照以下方式修改你的代码:

    int main(void)
    {
        const int n = 3;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                printf("#");
            }
            printf("\n");
        }
    }
    

    Notice how n is now a constant. It can never be changed.
    请注意, n 现在是一个常量,永远无法更改。

  • As illustrated earlier in this lecture, we can make our code prompt the user for the size of the grid. Modify your code as follows:
    正如本讲座前面所示,我们可以让代码提示用户输入网格大小。请按照以下方式修改您的代码:

    #include <cs50.h>
    #include <stdio.h>
    
    int main(void)
    {
        int n = get_int("Size: ");
    
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                printf("#");
            }
            printf("\n");
        }
    }
    

    Notice that get_int is used to prompt the user.
    请注意, get_int 用于提示用户。

  • A general piece of advice within programming is that you should never fully trust your user. They will likely misbehave, typing incorrect values where they should not. We can protect our program from bad behavior by checking to make sure the user’s input satisfies our needs. Modify your code as follows:
    在编程中,一个普遍的建议是永远不要完全信任用户。他们可能会误操作,在不应该的地方输入错误的值。我们可以通过检查用户输入是否符合我们的要求来保护程序免受不良行为的影响。请按照以下步骤修改代码:

    #include <cs50.h>
    #include <stdio.h>
    
    int main(void)
    {
        int n;
        do
        {
            n = get_int("Size: ");
        }
        while (n < 1);
    
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                printf("#");
            }
            printf("\n");
        }
    }
    

    Notice how the user is continuously prompted for the size until the user’s input is 1 or greater.
    注意,系统会持续提示用户输入大小,直到用户输入的值大于或等于 1 为止。

Comments 评语

  • Comments are fundamental parts of a computer program, where you leave explanatory remarks to yourself and others that may be collaborating with you regarding your code.
    注释是计算机程序中的基本组成部分,它们允许您向自己和与您合作的其他人留下关于代码的解释性说明。
  • All code you create for this course must include robust comments.
    您为本课程编写的代码必须包含详细的注释。
  • Typically each comment is a few words or more, providing the reader an opportunity to understand what is happening in a specific block of code. Further, such comments serve as a reminder for you later when you need to revise your code.
    通常,每条评论由几个字或更多组成,给读者提供了理解特定代码块中发生事情的机会。此外,这些评论也可以在您稍后修改代码时作为提醒。
  • Comments involve placing // into your code, followed by a comment. Modify your code as follows to integrate comments:
    注释需要在代码中添加 // ,然后添加注释。修改您的代码以集成注释,如下所示:

    #include <cs50.h>
    #include <stdio.h>
    
    int main(void)
    {
        // Prompt user for positive integer
        int n;
        do
        {
            n = get_int("Size: ");
        }
        while (n < 1);
    
        // Print an n-by-n grid of bricks
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                printf("#");
            }
            printf("\n");
        }
    }
    

    Notice how each comment begins with a //.
    请注意,每条评论都是以 // 开头的。

Types 类型

  • One of C’s shortcomings is the ease by which it managing memory. While C provides you immense control over how memory is utilized, programmers have to be very aware of potential pitfalls of memory management.
    C 语言的一个缺点是它在内存管理方面很容易出错。虽然 C 语言提供了对内存使用方式的极大控制,但程序员必须非常注意内存管理的潜在陷阱。
  • Types refer to the possible data that can be stored within a variable. For example, a char is designed to accommodate a single character like a or 2.
    类型是指可以存储在变量中的数据类型。例如, char 被设计为可以容纳类似 a2 的单个字符。
  • Types are very important because each type has specific limits. For example, because of the limits in memory, the highest value of an int can be 4294967295. If you attempt to count an int higher, integer overflow will result where an incorrect value will be stored in this variable.
    类型非常重要,因为每种类型都有特定的限制。例如,由于内存限制, int 的最大值是 4294967295 。如果尝试计算一个大于 4294967295int ,会导致整数溢出,从而导致此变量存储错误的值。
  • The number of bits limits how high and low we can count.
    位数限制了我们能计数的范围,即最高值和最低值。
  • Types with which you might interact during this course include:
    在这门课程中,您可能会接触到的类型包括:

    • bool, a Boolean expression of either true or false
      bool ,一个布尔表达式,结果为真或假
    • char, a single character like a or 2
      char ,像字母 a 或数字 2 这样的单个字符
    • double, a floating-point value with more digits than a float
      double ,一个浮点值,其数字位数超过普通浮点数
    • float, a floating-point value, or real number with a decimal value
      float ,一个浮点数,或带小数的实数
    • int, integers up to a certain size, or number of bits
      int ,最多到一定大小的整数,或位数
    • long, integers with more bits, so they can count higher than an int
      具有更多位的整数可以进行更高的计数
    • string, a string of characters
      string ,一串字符的文本
  • As you are coding, pay special attention to the types of variables you are using to avoid problems within your code.
    在编码时,请特别注意所使用的变量类型,以避免代码出现问题。
  • We examined some examples of disasters that can occur through memory-related errors.
    我们分析了一些可能因记忆相关错误而导致的灾难例子。

Summing Up 概括

In this lesson, you learned how to apply the building blocks you learned in Scratch to the C programming language. You learned…
在本节课中,您学习了如何将 Scratch 中学到的基本知识应用到 C 编程语言中。您还学到了…

  • How to create your first program in C.
    如何用 C 语言编写你的第一个程序。
  • Predefined functions that come natively with C and how to implement your own functions.
    C 语言自带的预定义函数,以及如何实现自定义函数。
  • How to use variables, conditionals, and loops.
    如何使用变量、条件语句和循环。
  • How to approach abstraction to simplify and improve your code.
    如何运用抽象来简化和优化你的代码。
  • How to approach problem-solving for a computer science problem.
    如何针对计算机科学问题进行有效的解决。
  • How to use the Linux command line.
    如何使用 Linux 命令行。
  • How to integrate comments into your code.
    如何在代码中添加注释。
  • How to utilize types and operators.
    如何使用类型和运算符。

See you next time!
下次见!