Yêu cầu:
– Cho mảng số thực và giá trị x
– Tìm phần tử trong mảng gần giá trị x nhất
Ví dụ:
– Cho mảng A gồm: {-12, 0, 4, 30, 7} và giá trị x = 17
– Khoảng cách từ x = 17 tới các phần tử trong mảng là: {29, 17, 13, 13, 10}
– Từ đây, ta xác định được 7 là phần tử gần x = 17 nhất
Giải thuật:
– Dùng vòng lặp duyệt mảng để tìm khoảng cách ngắn nhất từ x tới phần tử của mảng. Từ đây, ta tìm được chỉ số của phần tử mà khoảng cách tới x là nhỏ nhất
Code
/************************************************************ * Author: VNCODING * History * 2016/12/21 first create VNCODING *************************************************************/ #include <stdio.h> #include <conio.h> #include <math.h> #define MAX_SIZE_ARR 100 float get_element_nearest_x(float arr[], int sz, float x); int main() { float arr[MAX_SIZE_ARR], x, res; int n, i; do { printf("n = "); scanf("%d", &n); }while(n <= 0); // Input array for(i = 0; i < n; i++) { printf("\narr[%d] = ", i); scanf("%f", &arr[i]); } // Input x printf("x = "); scanf("%f", &x); res = get_element_nearest_x(arr, n, x); printf("%f is nearest from %f", res, x); getch(); return 0; } /******************************************************** * Description: get element in array that is nearest x * Parm: arr: array * sz: size of array * x: * Return: float element from array *********************************************************/ float get_element_nearest_x(float arr[], int sz, float x) { int i, idx = 0; float temp; float dist = abs(double(arr[0] - x)); for(i = 1; i < sz; i++) { temp = abs(double(arr[i] - x)); if(dist > temp) { dist = temp; idx = i; } } return arr[idx]; }
Kết quả:
Leave a Reply
You must be logged in to post a comment.