用三分法求给定数组的最大值、最小值、数组的和的C++代码
时间: 2023-03-27 16:04:51 浏览: 85
以下是用三分法求给定数组的最大值、最小值、数组的和的C代码:
```
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int a[n];
for (int i = ; i < n; i++) {
scanf("%d", &a[i]);
}
int l = , r = n - 1;
int max_val = a[], min_val = a[], sum = ;
while (l <= r) {
int mid = (l + r) / 2;
if (a[mid] > max_val) {
max_val = a[mid];
}
if (a[mid] < min_val) {
min_val = a[mid];
}
sum += a[mid];
if (mid == l && mid == r) {
break;
}
if (mid == l) {
l = mid + 1;
} else if (mid == r) {
r = mid - 1;
} else if (a[mid - 1] > a[mid + 1]) {
r = mid - 1;
} else {
l = mid + 1;
}
}
printf("最大值:%d\n", max_val);
printf("最小值:%d\n", min_val);
printf("数组的和:%d\n", sum);
return ;
}
```
阅读全文