c++查找最接近的元素

在一个非降序列中,查找与蒜头君的给定值最接近的元素。

img

img
我的代码:

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n;
    cin>>n;
    int a[10001000];
    for(int i=1;i<=n;i++) cin>>a[i];
    int m;cin>>m;
    for(int i=1;i<=m;i++)
    {
        int x;
        cin>>x;
        for(int j=1;j<=n;j++)
        {
            if(a[j]>=x)
            {
                if(abs(a[j]-x)<abs(a[j-1]-x)) cout<<a[j]<<endl;
                else cout<<a[j-1]<<endl;
                break;
            }
            if(j==n) cout<<a[n]<<endl;
        }
    }
    return 0;
}

这里:
(代码挺少,按照了你的格式)

#include <bits/stdc++.h>
#include <malloc.h>//其他编译器可能是stdlib.h,cstdlib

using namespace std;

int main(void){
    int n;
    cout << "in:";
    cin >> n;//数量
    int * m = (int*)malloc(sizeof(int) * n);
    for(int i =0;i < n;i++)cin >> m[i];
    int timec = 0;
    cout << "in:";
    cin >> timec;
    for(int i = 0;i < timec;i++){
        int z = 0;
        int nowMax = m[0];
        cout << "in:";
        cin >> z;
        for(int x = 0;x < n;x++){
            if(nowMax != m[x]){
                if(abs(m[x]-z) < abs(nowMax-z)){
                    nowMax = m[x];
                }
            }
        }
        cout << "o:" << nowMax << endl;
    }
    return 0;
}

输出:
in:10
1 3 5 8 9 10 11 25 14 56
in:3
in:10
o:10
in:12
o:11
in:24
o:25

是要代码吗

查找最接近的元素-算法学习_dalao_whs的博客-CSDN博客 查找最接近的元素 2020/11/26#include<iostream>using namespace std;//查找最接近的元素int a[100000];int b[10000];int n;int search(int t) { int left = 0, right = n-1; while (left < right) { if (a[left] == t || a[right] == t)//当查找到相同的数字时直接返回 { retu https://blog.csdn.net/dalao_whs/article/details/110202476