用c++实现统计数组中有多少个拐点
时间: 2023-06-18 09:04:31 浏览: 102
拐点指的是数组中出现“上升-下降”或“下降-上升”的位置,可以用以下代码实现:
```cpp
#include <iostream>
using namespace std;
int countTurningPoints(int arr[], int n) {
int count = 0;
for (int i = 1; i < n-1; i++) {
if ((arr[i] > arr[i-1] && arr[i] > arr[i+1]) ||
(arr[i] < arr[i-1] && arr[i] < arr[i+1]))
count++;
}
return count;
}
int main() {
int arr[] = {1, 2, 3, 2, 1, 5, 4, 3};
int n = sizeof(arr)/sizeof(arr[0]);
int count = countTurningPoints(arr, n);
cout << "Number of turning points: " << count << endl;
return 0;
}
```
输出结果为:Number of turning points: 4
阅读全文