#include <stdio.h> #include <stdlib.h> /* 给定一个含有n个元素的整型数组, 找出数组中的两个元素x和y使得abs(x - y)值最小 */ /* 思路: 排序, 然后遍历数组比较相邻值相减得到的值 */ typedef struct{ int num1; int num2; }TwoNumber; TwoNumber getTNumber(int* numbers, int length); int cmp(const void *a,const void *b); int abs(int number); int main(){ int n; while (printf("Please input n:\n"), fflush(stdin), scanf("%d", &n) != EOF){ if (n < 2){ printf("Please input a bigger number.\n"); continue; } int *numbers = (int*)malloc(n*sizeof(int)); printf("Please input %d numbers: \n",n); for (int i = 0; i < n; ++i) scanf("%d", numbers + i); TwoNumber tNumber = getTNumber(numbers,n); printf("%d %d\n",tNumber.num1,tNumber.num2); } system("pause"); return 0; } TwoNumber getTNumber(int* numbers, int length){ qsort(numbers,length,sizeof(int),cmp); int absMinus = abs(numbers[0] - numbers[1]); int index = 0; for (int i = 1; i < length - 1; ++i){ if (absMinus > abs(numbers[i] - numbers[i + 1])){ absMinus = abs(numbers[i] - numbers[i + 1]); index = i; } } TwoNumber tNumber; tNumber.num1 = numbers[index]; tNumber.num2 = numbers[index + 1]; return tNumber; } int cmp(const void *a, const void *b){ return *(int*)a - *(int*)b; } int abs(int number){ if (number > 0) return number; else return -number; }
时间: 2024-10-09 21:17:28