02-前导程序
4.1 前导程序
与前两章一样,本章以一个简单的程序开始。程序清单4.1与用户进行简单的交互。为了使程序的形式灵活多样,代码中使用了新的注释风格。
程序清单4.1 talkback.c 程序
// talkback.c -- 演示与用户交互
#include <stdio.h>
#include <string.h> // 提供strlen()函数的原型
#define DENSITY 62.4 // 人体密度(单位:磅/立方英尺)
int main()
{
float weight, volume;
int size, letters;
char name[40]; // name是一个可容纳40个字符的数组
printf("Hi! What's your first name?\n");
scanf("%s", name);
printf("%s, what's your weight in pounds?\n", name);
scanf("%f", &weight);
size = sizeof(name);
letters = strlen(name);
volume = weight / DENSITY;
printf("Well, %s, your volume is %2.2f cubic feet.\n",
name, volume);
printf("Also, your first name has %d letters,\n",
letters);
printf("and we have %d bytes to store it.\n", size);
return 0;
}
运行 talkback.c 程序,输入结果如下:
Hi! What's your first name?
Christine
Christine, what's your weight in pounds?
154
Well, Christine, your volume is 2.47 cubic feet.
Also, your first name has 9 letters,
and we have 40 bytes to store it.
该程序包含以下新特性。
- 用数组(array)存储字符串(character string)。在该程序中,用户输入的名被存储在数组中,该数组占用内存中40个连续的字节,每个字节存储一个字符值。
- 使用
%s转换说明来处理字符串的输入和输出。注意,在scanf()中,name没有&前缀,而weight有(稍后解释,&weight和name都是地址)。 - 用C预处理器把字符常量
DENSITY定义为62.4。 - 用C函数
strlen()获取字符串的长度。
对于BASIC的输入/输出而言,C的输入/输出看上去有些复杂。不过,复杂换来的是程序的高效和方便控制输入/输出。而且,一旦熟悉用法后,会发现它很简单。