二分搜索 float
Given a sorted array of floats, find the index of the number closest to x: Example: {1.2, 2.5, 9.3} x = 5, return 1
#include<iostream> #include<stdlib.h> #include <math.h> using namespace std; float a[] = {1.2, 2.6, 3.4, 4.2, 5.5, 6.7, 7.1, 8.5, 9.8, 9.9}; int main() { int n = sizeof(a)/sizeof(int); float f; cout << "Please input the number:" << endl; cin >> f; int low = 0; int high = n - 1; int mid; int index; float diff, diff_l, diff_r; while(low <= high) { int flag1 = 0; int flag2 = 0; mid = low + (high - low)/2; diff = (a[mid] - f) > 0 ? (a[mid] - f) : (f - a[mid]); if(mid - 1 >= low ) { diff_l = (a[mid - 1] - f) > 0 ? (a[mid - 1] - f) : (f -a[mid - 1]) ; flag1 = 1; } if(mid + 1 <= high){ diff_r = (a[mid + 1] - f) > 0 ? (a[mid + 1] -f) : (f - a[mid + 1]); flag2 = 1; } if(flag1 == 1 && flag2 == 1) { if (diff_l >= diff && diff_r >= diff) { index = mid; break; } if (diff_l < diff_r) { high = mid - 1; } else { low = mid + 1; } } else if(flag1 == 1) { if(diff_l >= diff) { index = mid ; break; } else { high = mid - 1; } } else if(flag2 == 1) { if (diff_r >= diff) { index = mid; break; } else { low = mid + 1; } } else { index = mid; break; } } cout << index << endl; return 0; }