You are on page 1of 31

C How to Program

李思
Chapter 2 Introduction to C Programming

C 语言程序设计入门
提纲
2.1 引言 Introduction
2.2 一个简单的 C 程序:打印一行文字 A Simple C Program: Pr
inting a Line of Text
2.3 另一个简单的 C 程序:两个整数求和 Another Simple C Pro
gram: Adding Two Integers
2.4 存储单元的基本概念 Memory Concepts
2.5 C 语言中的算术运算 Arithmetic in C
2.6 做出判断:相等和关系运算符 Decision Making: Equality
and Relational Operators
学习目标
 在本章中,读者将学习以下内容 :
 用 C 语言编写简单的计算机程序 (To be able to write simple computer prog
rams in C. )
 基本输入输出语句的使用 (To be able to use simple input and output stat
ements.)
 基本数据类型的使用 (To become familiar with fundamental data types.)
 计算机存储器的基本概念 (To understand computer memory concepts. )
 算术运算符的使用 (To be able to use arithmetic operators.)
 算术运算符的优先级 (To understand the precedence of arithmetic operato
rs.)
 编写简单的判断语句 (To be able to write simple decision making stateme
nts. )
2.1 引言

 C 语言 (C programming language)
 使程序设计更加结构化和规范化 (Structured and disciplined approa
ch to program design)

 结构化程序设计 (Structured programming)


 在第 3 章和第 4 章介绍 (Introduced in chapters 3 and 4)
 贯穿本书剩余部分 (Used throughout the remainder of the book)
2.2 一个简单的 C 程序:打印一行文字
1 /* Fig. 2.1: fig02_01.c
23 A first program in C */
Computer
#include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8 printf( "Welcome to C!\n" );
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */

 注释 (Comments)
 /* 和 */ 之间的文本不会引发计算的任何操作 (Text surrounded by
/* and */ is ignored by computer)
 用来描述程序 (Used to describe program)
2.2 一个简单的 C 程序:打印一行文字
1 /* Fig. 2.1: fig02_01.c
23 A first program in C */
Computer
#include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8 printf( "Welcome to C!\n" );
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */

 #include <stdio.h>
 预处理指令 (Preprocessor directive)
 告诉计算机将特定文件包含到源程序中 (Tells computer to load conte
nts of a certain file)
 <stdio.h>
允许标准输入 / 输出操作 (allows standard input/output operations)
2.2 一个简单的 C 程序:打印一行文字
1 /* Fig. 2.1: fig02_01.c
 Computer 2 A first program in C */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8 printf( "Welcome to C!\n" );
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */

 int main()
 C 程序由一个或多个函数组成,其中 main 函数是不可或缺的 (C++ programs contain one or
more functions, exactly one of which must be main )
 圆括号表明这是函数 (Parenthesis used to indicate a function)
 关键字 int 表示 main 函数执行后返回一个整数( int means that main "returns" an int
eger value)
 花括号及位于其内的程序段称为模块 (Braces ({ and }) indicate a block)
 所有函数的函数体必须包含在模块内 (The bodies of all functions must be contained
in braces)
2.2 A Simple C Program: Printing a Line of Text
1 /* Fig. 2.1: fig02_01.c
2 A first program in C */
3 Computer
#include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 { Welcome to C!
8 printf( "Welcome to C!\n" );
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */

 printf( "Welcome to C!\n" );


 命令计算机执行一个操作 (Instructs computer to perform an action)
 用 " " 来打印字符串 (Specifically, prints the string of characters within quotes (" "))
 一整行称为一条语句 (Entire line called a statement)
 每条语句都必须以分号结尾 (All statements must end with a semicolon (;))
 转义字符 (\) (Escape character (\))
 表明 printf 应该做些不一样的事情 (Indicates that printf should do something out
of the ordinary)
 \n 表示换行 (\n is the newline character)
2.2 一个简单的 C 程序:打印一行文字
Escape Sequence Description
\n Newline. Position the cursor at the beginning of the next line.
\t Horizontal tab. Move the cursor to the next tab stop.
\a Alert. Sound the system bell.
\\ Backslash. Insert a backslash character in a string.
\" Double quote. Insert a double quote character in a string.
Fig. 2.2 Some common escape sequences.

转义序列 描述
\n 换行,将光标移到下一行的起始位置
\t 水平制表,将光标移到下一个制表位置
\a 响铃报警,响起系统铃声
\\ 反斜线,在字符串中插入一个反斜线
\'' 双引号,在字符串中插入一个双引号

图 2.2 一些常用的转义序列
2.2 一个简单的 C 程序:打印一行文字
1
2
/* Fig.
Computer
 2.1: fig02_01.c
A first program in C */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 { Welcome to C!
8 printf( "Welcome to C!\n" );
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */

 return 0;
 退出函数手段之一 (A way to exit a function)
 返回 0 值表示程序成功终止 (return 0, in this case, means that the pr
ogram terminated normally)
 右花括号 } (Right brace })
 表示 main 函数到此结束 (Indicates end of main has been reached)
1 /* Fig. 2.3: fig02_03.c
2 Printing on one line with two printf statements */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8 printf( "Welcome " );
9 printf( "to C!\n" );
10
11 return 0; /* indicate that program ended successfully */
12
13 } /* end function main */

Welcome to C!
1 /* Fig. 2.4: fig02_04.c
2 Printing multiple lines with a single printf */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8 printf( "Welcome\nto\nC!\n" );
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */
Welcome
to
C!
2.3 另一个简单的 C 程序:两个整数求和
1 /* Fig. 2.5: fig02_05.c
2 Addition program */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8 int integer1; /* first number to be input by user */
输入第一个参数 45 (Enter
9 int integer2; /* second number to be input by user */
10 int sum; /* variable in which sum will be stored */
first integer 45)
11 输入第二个参数 72 (Enter
12 printf( "Enter first integer\n" ); /* prompt */ second integer 72)
13 scanf( "%d", &integer1 ); /* read an integer */
和为 117 (Sum is 117)
14
15 printf( "Enter second integer\n" ); /* prompt */
16 scanf( "%d", &integer2 ); /* read an integer */
17
18 sum = integer1 + integer2; /* assign total to sum */
19
20 printf( "Sum is %d\n", sum ); /* print sum */
21
22 return 0; /* indicate that program ended successfully */
23
24 } /* end function main */
 和以前一样 ( As before )
 注释, #include <stdio.h> 和 main 函数 (Comments, #include <stdi
o.h> and main)
 int integer1, integer2, sum;
 对变量的定义 (Definition of variables)
 变量 (Variables): 对应一个存储空间,存放数据 (locations in memory
where a value can be stored)
 int 表明变量的数据类型是整型 (int means the variables can hold intege
rs (-1, 3, 0, 47))
 变量名(标识符) (Variable names (identifiers))
 integer1, integer2, sum
 标识符 (Identifiers) : 由字母、数字和下画线组成的字符串 (consist of letters, digits (cannot
begin with a digit) and underscores( _ ))
 大小写敏感 (Case sensitive)

 变量定义必须在可执行语句之前 (Definitions appear before executable


statements)
 如果可执行语句引用了未声明的变量,会引起语法(编译)错误 (If an executable statement
references and undeclared variable it will produce a syntax (compiler) error)
 scanf( "%d", &integer1 );
 从用户那里获得一个数据 (Obtains a value from the user)
 scanf 从标准输入流(通常是键盘)中读入数据 (scanf uses standard input
(usually keyboard))

 scanf 函数有两个实参 (This scanf statement has two arguments)


 %d - 表示输入的数据是整数 (indicates data should be a decimal integer)
 &integer1 - 获取变量的存储地址 (location in memory to store variable)
 & is confusing in beginning – 将变量的存储地址告知 scanf 函数 (for now,
just remember to include it with the variable name in scanf statements)
 执行 scanf 函数时,用户键入一个数值并敲击回车键 (When executing the
program the user responds to the scanf statement by typing in a
number, then pressing the enter (return) key)
 = 分配运算符 (assignment operator)
 给变量赋值 (Assigns a value to a variable)
 二元运算符(有两个操作数) Is a binary operator (has two operands)
sum = variable1 + variable2;
sum gets variable1 + variable2;
 等号左边的变量接收值 (Variable receiving value on left)

 printf( "Sum is %d\n", sum );


 同 scanf 相似 (Similar to scanf)
 转换说明符 %d 表示会打印十进制整数 (%d means decimal integer will be printed)
 第二个实参 sum 规定了将要打印的数值 (sum specifies what integer will be printed)
 在 printf 语句中可以执行运算 (Calculations can be performed inside printf statements)
printf( "Sum is %d\n", integer1 + integer2 );
2.4 存储单元的基本概念
 变量 (Variables)
 变量名对应着计算机存储空间的一个存储单元 (Variable names correspond to
locations in the computer's memory)
 每个变量都具有三个属性:变量名、数据类型和数值 (Every variable has a na
me, a type, a size and a value)
 无论值何时存入存储单元,这个值将替换该存储单元原来存储的旧值 (Whenever a
new value is placed into a variable (through scanf, for example), it re
places (and destroys) the previous value)
 读出变量名不会改变它们 (Reading variables from memory does not change t
hem)

 直观表示 (A visual representation) integer1 45


integer1 45
integer1 45

integer2 72
integer2 72

sum 117
2.5 C 语言中的算术运算
 算术运算 (Arithmetic calculations)
 星号 * 表示乘法 ,/ 表示除法 (Use * for multiplication and / for
division)
 整数除法没有余数 (Integer division truncates remainder)
 7 / 5 = 1 (7 / 5 evaluates to 1)
 求余运算符 % 返回余数 (Modulus operator(%) returns the remaind
er)
 7 % 5 = 2 (7 % 5 evaluates to 2)
2.5 C 语言中的算术运算

 运算符优先级 (Operator precedence)


 一些算术运算符优先级高(例如,乘法先于加法) (Some arithmetic op
erators act before others (i.e., multiplication before additio
n))
 必要的时候使用圆括号 (Use parenthesis when needed)
 例如:求变量 a 、 b 、 c 的算术平均数 (Example: Find the average of
three variables a, b and c)
 Do not use: a + b + c / 3
 Use: (a + b + c ) / 3
2.5 C 语言中的算术运算
 Arithmetic operators:
C operation Arithmetic operator Algebraic expression C expression

Addition + f+7 f + 7

Subtraction - p–c p - c

Multiplication * bm b * m

Division / x/y x / y

Modulus % r mod s r % s

算术运算符

C 运算 算术运算符 代数表达式 C 表达式


加法 + f+7 f+7

减法 _ p-c p-c

乘法 * bm b*m

除法 / x/y x/y

求余数 % r mod s r%s


2.5 C 语言中的算术运算
 Rules of operator precedence:
Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is
evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not
nested), they are evaluated left to right.

*, /, or % Multiplication,Division, Evaluated second. If there are several, they are


Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.

算术运算符的优先级
运算符 对应的操作 计算顺序(优先级)
() 圆括号 优先级最高。如果有嵌套的圆括号,则先计算最内层圆括号内
的表达式。如果同一层内有多对并列的而非嵌套的圆括号,则
从左向右计算。
* 乘法 优先级次之。如果有多个,则从左向右计算
/ 除法
%
求余
+ 加法 优先级最低。如果有多个,则从左向右计算
- 减法
2.6 做出判断:相等和关系运算符
 可执行语句 (Executable statements)
 执行操作(运算,输入 / 输出操作) (Perform actions (calculations,
input/output of data))
 做出判断 (Perform decisions)
 输入一个测试成绩,会打印出“通过”或者“失败” (May want to print "pass" or
"fail" given the value of a test grade)
 if 控制语句 (if control statement)
 这节简单介绍,下一章更详尽 (Simple version in this section, more detail later)
 如果条件为 true ,则执行 if 语句体中的语句 (If a condition is true, then the body of the
if statement executed)
 0 表示“假” , 非 0 表示“真” (0 is false, non-zero is true)

 if 语句执行结束后,计算机执行紧随 if 语句的下一条语句 (Control always resumes after the


if structure)
2.6 做出判断:相等和关系运算符
 关键字 (Keywords)
 C 语言中的特殊单词 (Special words reserved for C)
 不能作为标识符或者变量名 (Cannot be used as identifiers or variable names)
2.6 做出判断:相等和关系运算符
Standard algebraic equality C equality or Example of C Meaning of C condition
operator or relational operator relational operator condition
Equality Operators
==
= x == y x is equal to y

 != x != y x is not equal to y

Relational Operators
>
> x > y x is greater than y

<
< x < y x is less than y

>=
>= x >= y x is greater than or equal to y

<=
<= x <= y x is less than or equal to y

代数相等运算符 C 相等或比较运 C 条件的例子 C 条件的含义


或比较运算符 算符
相等运算符
= == x == y x 等于 y
≠ != x != y x 不等于 y
相等和关系运算符
关系运算符
> > x>y
x<y x 大于 y
< <
>= x >= y x 小于 y

≤ <= x <= y x 大于或者等于 y
x 小于或者等于 y
运算符 结合律
() 从左向右
*/% 从左向右
+- 从左向右
< <= > >= 从左向右
== != 从左向右
= 从右向左

迄今介绍过的运算符的优先级和结合律
1 /* Fig. 2.13: fig02_13.c 25 if ( num1 < num2 ) {
2 Using if statements, relational 26 printf( "%d is less than %d\n", num1, num2 );
3 operators, and equality operators */ 27 } /* end if */
4 #include <stdio.h> 28
5 29 if ( num1 > num2 ) {
6 /* function main begins program execution */ 30 printf( "%d is greater than %d\n", num1, num2 );
7 int main() 31 } /* end if */
8 { 32
9 int num1, /* first number to be read from user */ 33 if ( num1 <= num2 ) {
10 int num2; /* second number to be read from user */ 34 printf( "%d is less than or equal to %d\n", num1, num2 );
11 35 } /* end if */
12 printf( "Enter two integers, and I will tell you\n" ); 36
13 printf( "the relationships they satisfy: " ); 37 if ( num1 >= num2 ) {
14 38 printf( "%d is greater than or equal to %d\n", num1, num2 );
15 scanf( "%d%d", &num1, &num2 ); /* read two integers */ 39 } /* end if */
16 40
17 if ( num1 == num2 ) { 41 return 0; /* indicate that program ended successfully */
18 printf( "%d is equal to %d\n", num1, num2 ); 42
19 } /* end if */ 43 } /* end function main */
20
21 if ( num1 != num2 ) { Enter two integers, and I will tell you
22 printf( "%d is not equal to %d\n", num1, num2 ); the relationships they satisfy: 22 12
23 } /* end if */
22 is not equal to 12
24
22 is greater than 12
22 is greater than or equal to 12
Enter two integers, and I will tell you
the relationships they satisfy: 3 7
Enter two integers, and I will tell you
3 is not equal to 7
the relationships they satisfy: 7 7
3 is less than 7
7 is equal to 7
3 is less than or equal to 7
7 is less than or equal to 7
7 is greater than or equal to 7

You might also like