在C++中,要搜索一个双精度数组中的最近值,可以使用以下方法:
#include<iostream>
#include<vector>
#include <cmath>
#include<limits>
using namespace std;
double distance(double a, double b) {
return abs(a - b);
}
double findNearestValue(const vector<double>& arr, double target) {
double nearestValue = arr[0];
double minDistance = distance(arr[0], target);
for (size_t i = 1; i < arr.size(); ++i) {
double currentDistance = distance(arr[i], target);
if (currentDistance < minDistance) {
minDistance = currentDistance;
nearestValue = arr[i];
}
}
return nearestValue;
}
findNearestValue
函数来搜索最近值:int main() {
vector<double> arr = {1.0, 2.0, 3.0, 4.0, 5.0};
double target = 3.5;
double nearestValue = findNearestValue(arr, target);
cout << "The nearest value to "<< target << " is "<< nearestValue<< endl;
return 0;
}
这个程序将会输出:
The nearest value to 3.5 is 3
这个方法可以用于任何双精度数组,只需将其传递给findNearestValue
函数即可。
领取专属 10元无门槛券
手把手带您无忧上云