在一个非降序列中,查找与蒜头君的给定值最接近的元素。
我的代码:
#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
是要代码吗