Rockiswu 2021-08-15 08:16 采纳率: 87.9%
浏览 776
已结题

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;
}

  • 写回答

3条回答 默认 最新

  • aaaa0ggMC 2021-08-15 09:27
    关注

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

    #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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 8月23日
  • 已采纳回答 8月15日
  • 创建了问题 8月15日

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)