输入一些数字,求哪些对数字差值最小:
#include <stdio.h>
#define max 10
int main()
{
int arr[max] = { 0 };
for (int i = 0; i < max; i++)//可以无序输入
{
scanf("%d", &arr[i]);
}
for (int i = 0; i < max - 1; i++)//先排序,这里是冒泡排序
{
for (int j = 0; j < max - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
int min_diff = arr[1] - arr[0];
int ans[max * 2 - 2] = { 0 };
int count = 0;
for (int i = 1; i < max; i++)//求最小差值,不断更新最小差值
{
int diff = arr[i] - arr[i - 1];
if (diff < min_diff)//出现更小差值时,ans数组全部更新
{
min_diff = diff;
count = 0;
ans[count++] = arr[i - 1];
ans[count++] = arr[i];
}
else if (diff == min_diff)//出现差值相等的一对数值
{
ans[count++] = arr[i - 1];
ans[count++] = arr[i];
}
}
for (int i = 0; i < count; i++)//打印
{
printf("%d ", ans[i]);
if ((i + 1) % 2 == 0)//每对一行
{
printf("\n");
}
}
return 0;
}