如何用C语言编写程序,实现产生0-100间的随机数,并且在这些数中查找离50最近的5个数?

谢了!
2024-12-22 00:37:31
推荐回答(1个)
回答1:

#include
#include
#include
#define BASE_NUMBER 50
#define ARRY_SIZE 20 //must large than 5
int compare(const void* l, const void* r); //以50为基数进行快速排序
int main(int argc, char *argv[])
{
int a[ARRY_SIZE];
int i;
for (i=0; i{
a[i] = rand()%100; //产生ARRY_SIZE个 0-100 的随机数
}
qsort(a, ARRY_SIZE, sizeof(int), compare);
printf("%d %d %d %d %d\n", a[0], a[1], a[2], a[3], a[4]);
return 0;
}
int compare(const void* l, const void* r)
{
int lv = *(int*)l;
int rv = *(int*)r;
if (abs(lv-BASE_NUMBER) > abs(rv-BASE_NUMBER))
{
return 1;
}
else if(abs(lv-BASE_NUMBER) < abs(rv-BASE_NUMBER))
{
return -1;
}
else
{
return 0;
}
}