求数组中的两个波峰的值
有一直方图:
数据存储在value[255]数组中,现在要求两个波峰对应的x的值;
请问:怎样求解???
[解决办法]
- C/C++ code
#include <iostream>#include <cstdlib>#include <ctime>using namespace std;#define MAX 1000int main() { double value[255]; srand( (unsigned)time(NULL) ); for(int i=0; i<255; ++i) value[i]=( rand()%MAX )/10.0; int first=0, second=0; //the objective x coordinate value double max_val=value[0], sub_val=value[0]; for(int i=0; i<255; ++i) { if(max_val<value[i]) { sub_val=max_val; max_val=value[i]; second=first; first=i; } else if(sub_val<value[i] && max_val>value[i]) { sub_val=value[i]; second=i; } else {} } cout<<first<<ends<<max_val<<endl; cout<<second<<ends<<sub_val<<endl; return 0;}
[解决办法]
或许这样好点,如果value已经存在,直接调用函数Search()就好了。
- C/C++ code
#include <iostream>#include <cstdlib>#include <ctime>using namespace std;#define MAX 1000void Search(double *value, int len){ int first=0, second=0; //the objective x coordinate value double max_val=value[0], sub_val=value[0]; for(int i=0; i<len; ++i) { if(max_val<value[i]) { sub_val=max_val; max_val=value[i]; second=first; first=i; } else if(sub_val<value[i] && max_val>value[i]) { sub_val=value[i]; second=i; } else {} } cout<<first<<ends<<max_val<<endl; cout<<second<<ends<<sub_val<<endl;}int main() { double value[255]; srand( (unsigned)time(NULL) ); for(int i=0; i<255; ++i) value[i]=( rand()%MAX )/10.0; //initialize the array Search(value, 255); return 0;}
[解决办法]
- C/C++ code
#include <stdio.h>#include <stdlib.h>#include <time.h>int search(const double *value, size_t len, int *ndx1, int *ndx2){ if (value == NULL || len == 0) { return -1; } double h1, h2; *ndx1 = *ndx2 = 0; h1 = h2 = value[0]; for (int i = 1; i < len; ++ i) { if (value[i] > h1) { h2 = h1; *ndx2 = *ndx1; h1 = value[i]; *ndx1 = i; } else if (value[i] > h2) { h2 = value[i]; *ndx2 = i; } } return 0;}int main(){ double value[255]; int ndx1, ndx2; srand((unsigned int)time(NULL)); for (int i = 0; i < 255; ++ i) { value[i] = rand() * 1.72 / RAND_MAX; } if (search(value, 255, &ndx1, &ndx2) == 0) { printf("value[%d]:%lf, value[%d]:%lf\n", ndx1, value[ndx1], ndx2, value[ndx2]); } return 0;}