题目描述:
要从5个人中选取2个人作为礼仪,其中每个人的身高范围为160-190,要求2个人的身高差值最小(如果差值相同的话,选取其中最高的两人),以升序输出两个人的身高。
Sample input: 161 189 167 172 188
Sample output: 188 189
代码:
#include <iostream>
#define NUM 5
#define SUBNUM 2
using namespace std;
void Sele_Peo(int* height, int num, int* people)
{
int i,j;
for (i = 0; i < num - 1; i++)
{
for (j = i + 1; j<num; j++)
{
if (height[i]>height[j])
{
int temp = height[i];
height[i] = height[j];
height[j] = temp;
}
}
}
int min = height[1] - height[0];
int flag = 0;
for (i = 1; i<num - 1; i++)
{
if (height[i + 1] - height[i] <= min)
{
flag = i;
}
}
people[0] = height[flag];
people[1] = height[flag + 1];
}
int main()
{
int height[NUM],people[SUBNUM];
int i=0;
char temp = '0';
while (temp != '\n'&&i < NUM)
{
cin >> height[i];
temp = getchar();
i++;
}
Sele_Peo(height, NUM, people);
for (i = 0; i < SUBNUM; i++)
{
cout << people[i];
if (i != SUBNUM - 1)
{
cout << ' ';
}
else
{
cout << endl;
}
}
cin.get();
return 0;
}