1 (此段内容来自原书,在此向原作者表示感谢)When I write large programs, I use long names (ten or twenty characters) for my global variables. This column uses short variable names such as x, n and t. In most software projects, the shortest plausible names might be more like elem, nelems and target. I find the short names convenient for building scaffolding and essential for mathematical proofs like that in Section 4.3. Similar rules apply to mathematics: the unfamiliar may want to hear that ``the square of the hypotenuse of a right triangle is equal to the sum of the squares of the two adjacent sides'', but people working on the problem usually say ``a^2 + b^2= c^2''. I've tried to stick close to Kernighan and Ritchie's C coding style, but I put the first line of code with the opening curly brace of a function and delete other blank lines to save space (a substantial percentage, for the little functions in this book).The binary search in Section 5.1 returns an integer that is -1 if the value is not present, and points to the value if it is present. Steve McConnell suggested that the search should properly return two values: a boolean telling whether it is present, and an index that is used only if the boolean is true:
boolean BinarySearch(DataType TargetValue, int *TargetIndex)
/* precondition: Element[0] <= Element[1] <=
... <= Element[NumElements-1]
postcondition:
result == false =>
TargetValue not in Element[0..NumElements-1]
result == true =>
Element[*TargetIndex] == TargetValue
*/
Listing 18.3 on page 402 of McConnell's Code Complete is a Pascal Insertion Sort that occupies one (large) page;the code and comments are together 41 lines. That style is appropriate for large software projects. Section 11.1 of this book presents the same algorithm in just five lines of code.Few of the programs have error checking. Some functions read data from files into arrays of size MAX, and scanfcalls can easily overflow their buffers. Array arguments that should be parameters are instead global variables.
Throughout this book, I've used shortcuts that are appropriate for textbooks and scaffolding, but not for large software projects. As Kernighan and Pike observe in Section 1.1 of their The Practice of Programming, ``clarity is often achieved through brevity''. Even so, most of my code avoids the incredibly dense style illustrated in the C++ code in Section 14.3.
2 一直用java从未被超越,java定义数组长度时可以使用变量来定义。妨碍么……写这个程序还没发现什么。
3 看这个题目想起了不久前鄙人一位基友叫我帮忙找他程序中的一个错误,这段程序他自己测试没什么问题,但是提交给服务器却不能通过,灰常可惜这段程序木有保存下来。只记得鄙人当时一时也没看出来,就写了个循环把程序合法输入的1000个数字测试了一遍发现了在某些数字会出现错误,而鄙人这位基友并没有测试过这几个数字而是随机测试了几个数字,导致没有发现错误。
4 首先验证输入的合法性,判断待检索数组是否升序或者降序排列。
5 很明显上一题鄙人给出的答案太含糊,没说明具体怎么做。题目说每次搜索前都要检测整个数组是否有序,因此可以声明一个变量来记录这个数组是否经过了检测。