查詢函式的值最接近於 C++ 中的 A 的給定列表中的數字
假設我們有一個函式 F(n) 使得 F(n) = P – (0.006*n),其中 P 也已給出。給定一個整數列表和一個數字 A。任務是查詢給定列表中的數字,使其函式值最接近 A。因此,如果 P = 12且 A = 5,則列表將為 {1000, 2000} 所以輸出將為 1000。因此,如果 P = 12 且 A = 5,則對於 1000,F(1000) = 12 – (0.006 * 1000) = 6 而對於 2000,F(2000) = 12 – (0.006 * 2000) = 0,因為最接近 5 的值為 6,所以取 6。
遍歷列表中的每個值,並找出每個值的 F(n)。現在比較 F(n) 的每個值與 A 的絕對差以及 n 的值,對於絕對差最小的 n,將是答案。
示例
#include<iostream>
#include<cmath>
using namespace std;
int nearestValue(int P, int A, int N, int arr[]) {
int ans = -1;
float temp = (float)INFINITY;
for (int i = 0; i < N; i++) {
float term = P - arr[i] * 0.006;
if (abs(term-A) < temp) {
temp = abs(term - A);
ans = i;
}
}
return arr[ans];
}
int main() {
int P = 12, A = 5;
int array[] = {1000, 2000, 1001};
int N = sizeof(array)/sizeof(array[0]);
cout << "Nearest value is: " << nearestValue(P, A, N, array) << endl;
}輸出
Nearest value is: 1001
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP