1.3 程序3:清晨的惊奇
这个程序是由我的一个朋友编写的,那时我们都在上大学。有一次,老师安排的课后作业是编写一个矩阵相乘(matrix-multiply)的例程。而且,这个矩阵相乘的函数本身要求必须使用汇编语言来编写。为了使程序的运行速度尽可能地快,他使用了我设计的一个算法,该算法向量化了矩阵。
为了测试这个程序,他利用SAIL编写了一个简短的测试函数。当我们测试这个程序时,却得到了一个错误答案。我们两个人从晚上8点到第二天凌晨2点仔细检查了该程序中的每行代码。最后,当我们找到错误时,都疯狂大笑起来,因为那是一个如此低级的错误。
注:
SAIL是一个用于PDP-10的旧式系统编程语言,其调试器称为BAIL。后来,在该语言的基础上创建了与机器无关的独立版本,名为MAIN
SAIL。该版本的面世时间比C语言还要早几年。
下面这个程序是前面所提到的“知名”代码的简化版本。该程序完全由一种语言(C语言)编写,且使用非常简单的乘法算法。但是,最初的bug仍然存在。结果会如何呢?
1 /***********************************************
2 * matrix-test -- Test matrix multiply ?*
3 ***********************************************/
4 #include <stdio.h>
5
6 /***********************************************
7 * matrix_multiply -- Multiple two matrixes ???????*
8 ***********************************************/
9 static void matrix_multiply(
10 int result[3][3], /* The result */
11 int matrix1[3][3],/* One multiplicand */
12 int matrix2[3][3] /* The other multiplicand */
13 )
14 {
15 /* Index into the elements of the matrix */
16 int row, col, element;
17
18 for(row = 0; row < 3; ++row)
19 {
20 for(col = 0; col < 3; ++col)
21 {
22 result[row][col] = 0;
23 for(element = 0; element < 3; ++element)
24 {
25 result[row][col] +=
26 matrix1[row][element] *
27 matrix2[element][col];
28 }
29 }
32 }
33 }
34
35 /**********************************************
36 * matrix_print -- Output the matrix ???????*
37 **********************************************/
38 static void matrix_print(
39 int matrix[3][3] /* The matrix to print */
40 )
41 {
42 int row, col; /* Index into the matrix */
43
44 for (row = 0; row < 3; ++row)
45 {
46 for (col = 0; col < 3; ++col)
47 {
48 printf("%o\t", matrix[row][col]);
49 }
50 printf("\n");
51 }
52 }
53
54 int main(void)
55 {
56 /* One matrix for multiplication */
57 int matrix_a[3][3] = {
58 {45, 82, 26},
59 {32, 11, 13},
60 {89, 81, 25}
61 };
62 /* Another matrix for multiplication */
63 int matrix_b[3][3] = {
64 {32, 43, 50},
65 {33, 40, 52},
66 {20, 12, 32}
67 };
68 /* Place to put result */
69 int result[3][3];
70
71 matrix_multiply(result, matrix_a, matrix_b);
72 matrix_print(result);
73 return (0);
74 }
75
(请参见“提示34”和“答案53”)
|