1.2 程序2:老师的问题
我曾经讲授过C程序设计课程。这里的问题是我制定的第一个测试卷中的第一个问题。我的意图很简单:想看看学生是否知道自动(automatic)变量和静态(static)变量之间的不同之处:
16 int i=0;
26 static int i=0;
不过,测试之后,我也不禁感到困惑:如果我自己做这个试题,也不能得出正确答案。因此,我就当作每个学生的面,告诉他们:“对于第一个问题,有两种得分方式。第一种就是给出正确答案;另一种是给出我认为是正确的答案。”
那么,正确答案是什么呢?
1 /***********************************************
2 * Test question: ?? ? *
3 * What does the following program print? ? *
4 * ? *
5 * Note: The question is designed to tell if ? *
6 * the student knows the difference between ? *
7 * automatic and static variables. ??? ?? ??*
8 *********************************************/
9 #include <stdio.h>
10 /**********************************************
11 * first -- Demonstration of automatic *
12 * variables. ??*
13 **********************************************/
14 int first(void)
15 {
16 int i = 0; // Demonstration variable
17
18 return (i++);
19 }
20 /**********************************************
21 * second -- Demonstration of a static ?*
22 * variable. ?? *
23 **********************************************/
24 int second(void)
25 {
26 static int i = 0; // Demonstration variable
27
28 return (i++);
29 }
30
31 int main()
32 {
33 int counter; // Call counter
34
35 for (counter = 0; counter < 3; counter++)
36 printf("First %d\n", first());
37
38 for (counter = 0; counter < 3; counter++)
39 printf("Second %d\n", second());
40
41 return (0);
42 }
(请参见“提示139”和“答案102”)
花絮
一个教堂购买了第一台计算机后,其神职人员都开始学习如何使用它。神父的助手决定在计算机中建立一个用于葬礼服务的套用信函,而且她还在埋葬人员姓名所在的位置放入一个单词:<name>。当需要主持葬礼时,她就用逝世人员的实际名称替换这个单词。
一天,先后有两个葬礼,第一葬礼的主人是Mary女士,后面一个是叫作Edna的人。于是,神父的助手首先就将<name>全部替换为Mary。到此,一切都没有问题。接着,她为第二个葬礼准备悼词,其方法就是将上一份信函中的Mary全部替换为Edna。结果,错误出现了。
您可以想像得到,当神父开始宣读包含Apostles’ Creed(信徒信条,意为“全能的父…”)部分,并看到“Born
of the Virgin Edna”这样的短语时是多么的吃惊(编者按:圣经中常用到Virgin Mary,即圣母码利亚——
耶稣之母,而没有Virgin Edna一说)。
|