14.4 单文件综合示例:求数组最大值
下面的程序综合使用数组、循环、选择、sizeof、断言和格式化输出。它适合在完成第 14 章后阅读,不作为第一个 C 程序。
c
#include <assert.h>
#include <float.h>
#include <stdio.h>
int main(void) {
double maximum = -DBL_MAX;
double numbers[6] = {
[0] = 1,
[2] = 2.26,
[3] = (double)(5 / 2),
[4] = .1,
[5] = 3.E-2
};
size_t count = sizeof numbers / sizeof numbers[0];
assert(count == 6);
for (size_t i = 0; i < count; ++i) {
if (numbers[i] > maximum) {
maximum = numbers[i];
}
}
printf("The maximum in the %zu numbers is %g\n", count, maximum);
return 0;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
输出:
bash
The maximum in the 6 numbers is 2.26
(double)(5 / 2) 先执行整数除法,再把结果转换为 double,因此数组中的该元素是 2.0,不是 2.5。