Skip to content

Types and arithmetic

C Programming Lesson 2 2:29 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
In C, every variable has a type, and you say what it is when you make it. 在 C 里,每个变量都有类型,而且你在创建它时就要说明是什么类型。
An int holds a whole number. int 装整数。
A double holds a decimal. double 装小数。
A char holds a single character, in single quotes. char 装单个字符,写在单引号里。
You state the type once, at the declaration, and from then on that box can never hold anything else — which is why the compiler can catch so much before the program runs. 类型只在声明时说明一次,从那以后这个盒子就再也装不了别的东西—— 正因如此,编译器才能在程序运行之前发现那么多问题。
Now the thing that catches everyone. 现在说那个几乎人人中招的地方。
When both sides are ints, C divides like whole numbers: ten over three is three, not three point three. 当两边都是 int 时,C 按整数来做除法: 10 除以 3 得到 3,而不是 3.33。
Make one side a decimal — write three point zero instead of three — and the whole calculation becomes a decimal one. 把其中一边变成小数——写 3.0 而不是 3——整个计算就变成小数运算。
There is no error and no warning; the fractional part is simply thrown away. 这里没有错误提示,也没有警告;小数部分直接被丢掉。
That is why the average task in this lesson divides by three point zero. 这就是为什么这一课的求平均题要除以 3.0。
To read a value you use scanf, and it needs two things. 要读入一个值,就用 scanf,它需要两样东西。
First, a format telling it what kind to read — percent d for a whole number, the same letters printf uses. 第一,一个格式说明它要读什么类型——%d 表示整数,和 printf 用的字母一样。
Second, and this is new, an ampersand before the variable name. 第二,这一点是新的:变量名前面要加一个 & 符号。
That ampersand means where to put it: you are handing scanf the ADDRESS of your variable, not its value. 这个符号的意思是“放到哪里”:你交给 scanf 的是变量的地址,而不是它的值。
Leave it out and the program will usually crash. 漏掉它,程序通常会崩溃。
Now the lesson's first task, and it is where integer division earns its keep. 现在做课程里的第一道题,而这正是整数除法发挥作用的地方。
A box holds six items, and you are told a count. 一个盒子装 6 件,给你一个总数。
How many full boxes? 有多少个装满的盒子?
Divide, and let the division truncate — that is exactly right, because a part-filled box is not a full one. 做除法,让它截断——这正好是对的,因为装不满的盒子不算装满。
Then percent gives what is left over. 然后用取余算出剩下几件。
Twenty items make three full boxes with two left. 20 件装满 3 盒,还剩 2 件。
The pair, slash and percent, answers both halves of the question. 斜杠和百分号这一对,回答了问题的两半。
Four things to take with you. 带走四点。
One: declare the type once — int, double or char — and it never changes. 第一:类型只声明一次——int、double 或 char——之后不再改变。
Two: an int over an int gives an int, so the decimals are dropped silently. 第二:int 除以 int 得到 int,小数部分会被悄悄丢掉。
Three: percent gives the remainder, and it pairs with the slash. 第三:百分号给出余数,它和斜杠是一对。
Four: scanf needs the ampersand, because it must be told where to put the value. 第四:scanf 需要 & 符号,因为必须告诉它把值放到哪里。
Now do the three tasks; the second one needs three point zero. 现在去做那三道题;第二题需要用 3.0。

Log in or create account

IGCSE, A-Level & AP