2.4 程序7:错误的平方
下面是一个简短的程序,可计算并输出1至5之间的数字的平方。这个程序很简单,难道也会有错误?
1 /************************************************
2 * squares -- Print the squares of the numbers *
3 * from 1 to 5. *
4 ************************************************/
5 #include <iostream>
6
7 int main()
8 {
9 // An array for the squares
10 int array[5];
11
12 int i; // Index into the array
13
14 for (i = 1; i <= 5; ++i) {
15 array[i] = i*i;
16 }
17
18 for (i = 1; i <= 5; ++i) {
19 std::cout << i << " squared is "
<<
20 array[i] << '\n';
21 }
22 return (0);
23 }
(请参见“提示103”和“答案90”)
花絮
在家美国公司的机房发现下面一段文字:
ACHTUNG! ALLES LOOKENSPEEPERS!
Das computermachine ist nicht fuer gefingerpoken und mittengrabben.
Ist
easy schnappen der springenwerk, blowenfusen und poppencorken
mit
spitzensparken. Ist nicht fuer gewerken bei das dumpkopfen.
Das rubbernecken
sichtseeren keepen das cotten-pickenen hans in das pockets
muss;
relaxen und watchen das blinkenlichten.
2.5 程序8:“疯狂”的字符
一个编程新手决定检查如何使用带char变量的if语句。下面的程序简单明了,但仍存在错误。
1 /************************************************
2 * Check the flag. ?*
3 ************************************************/
4 #include <iostream>
5
6 int main()
7 {
8 char ch; // The flag
9
10 ch = 0xFF; // Set the flag
11
12 // Check the flag
13 if (ch == 0xFF)
14 std::cout << "Success\n";
15 else
16 std::cout << "Fails\n";
17
18 return (0);
19 }
(请参见“提示131”和“答案8”)
花絮
在一家德国公司的机房中,发现了下面的一段文字:
ATTENTION
This room is fullfilled mit special electronische equippment.
Fingergrabbing
and pressing the cnoeppkes from the computers is allowed
for die
experts only! So all the “lefthanders” stay away and do not
disturben the
brainstorming von here working intelligencies. Otherwise
you will be out
thrown and kicked anderswhere! Also: Please keep still and
only watchen
astaunished the blinkenlights.
2.6 程序9:注释的问题
下面这个程序计算三角形的面积。其中的公式很简单,程序也很简单。很明显,程序的各个部分都能很好地运行。但是,该程序代码中仍然潜伏了一个令人吃惊的错误。
1 /************************************************
2 * triangle -- Compute the area of a triangle ? *
3 ************************************************/
4 #include <iostream>
5 int main()
6 {
7 int base = 0; /* Base of the triangle */
8 int height = 0; /* Height of the triangle */
9
10 base = 5; /* Set the base of the triangle
11 height = 2; /* Set the height */
12
13 // Area of the triangle
14 int area = (base * height) / 2;
15
16 std::cout << "The area is " <<
17 area << std::endl;
18 return (0);
19 }
(请参见“提示41”和“答案62”)
花絮
一个系统管理员碰到了许多关于网络路由器的故障。诸如E6和B2这样的奇怪错误号都出现在计算机屏幕上。于是,他打电话给厂商,要求技术服务。下面是这个名为Sysadmin的管理员与厂商技术支持人员的对话。
Sysadmin:“您能告诉我代码E6意味着什么样的错误?”
技术人员:“通信线路6上有一个短路现象。”
Sysadmin:“哪儿说明了这一点?”
技术人员:“在技术参考手册中。”
Sysadmin:“现在我有很多问题,您能不能向我传真一份那个参考手册?”
技术人员(不情愿地):“哦!好吧,但是它只有一份,您用完之后要再传真给我。”
|