pxxfxxxxx

导航

阵列(3)

19.5 用保留值标记阵列长度

保留值(这个值可以设定):0,-1,

 1 #include <stdio.h>
 2 int maxv(int[]);
 3 
 4 int main() {
 5     int a[4] = {1, 3, 4, -1}; // 这里的-1表示保留值
 6     printf("Max: %d\n", maxv(a));
 7     int b[6] = {6, 9, 7, 8, 3, -1};
 8     printf("Max: %d\n", maxv(b));
 9     return 0;
10 }
11 
12 int maxv(int v[]) {
13     int max = v[0], i = 1;
14     while (v[i] != -1) {
15         if (v[i] > max) {
16             max = v[i];
17         }
18         i++;
19     }
20     return max;
21 }
22 
23 Max: 4
24 Max: 9
25 
26 Process returned 0 (0x0)   execution time : 12.892 s
27 Press any key to continue.
 1 #include <stdio.h>
 2 int length(int[]);
 3 
 4 int main() {
 5     int v[] = {1, 2, 3, -1};
 6     printf("%d\n", length(v));
 7     return 0;
 8 }
 9 
10 int length(int v[]) {
11     int i = 0;
12     while (v[i] != -1) {
13         i++;
14     }
15     return i; // 此时的i表示的是资料型别多少个,而数组长度为 i+1
16 }
17 
18 3
19 
20 Process returned 0 (0x0)   execution time : 4.187 s
21 Press any key to continue.

 

posted on 2019-05-14 19:24  pxxfxxxxx  阅读(134)  评论(0编辑  收藏  举报