题目的意思就是先给出一组数。
然后给出要计算的数的个数,
算出上面给出的一组数中,任意两个相加,得到的值中和要计算的那个数最接近的是哪个,
枚举即可;
AC代码:
#include<iostream>
#include<cmath>
using namespace std;
int num[1000 + 5];
int main () {
int n;
int t;
int tar;
int res;
int T = 1;
while (cin >> n && n) {
for (int i = 0 ; i < n ;i++) {
cin >> num[i];
}
cin >> t;
cout << "Case " << T++ << ":\n";
for (int i = 0 ; i < t ;i++) {
cin >> tar;
int m = abs(num[0] + num[1] - tar);
res = m + tar;
for (int j = 0 ; j < n ;j++) {
for (int k = j + 1; k < n ;k++) {
if (abs(num[j] + num[k] - tar) < m) {
m = abs(num[j] + num[k] - tar);
res = num[j] + num[k];
}
}
}
cout <<"Closest sum to "<< tar << " is "<< res <<"."<<endl;
}
}
}