此代码有效,但它不是我想要的。有谁知道如何在没有 q 排序的情况下使其正确吗?这个想法是为了了解如何使用指针。 这三个数字应该在 -3 到 12 之间随机。下面的代码是类似的,也是我找到的最接近的。任何帮助将非常感激。提前致谢!!。
#include <stdio.h>
#include <stdlib.h>
//functions
int compare(const void *a, const void *b)
{
const int *ia = a;
const int *ib = b;
if (*ia < *ib)
return -1;
else if (*ia > *ib)
return +1;
return 0;
}
//qsort function
void sort3(int *a, int *b, int *c)
{
int temp[3];
temp[0] = *a;
temp[1] = *b;
temp[2] = *c;
qsort(temp, 3, sizeof(int), &compare);
*a = temp[0];
*b = temp[1];
*c = temp[2];
}
//random function
int rand_int(int a, int b)
{
return rand()%(b-a+1)+a;
}
int main(void)
{
//declaration of variables
int a,b,c;
int rand_int(int a, int b);
srand(time(0));
a = rand_int(-3,12);
b = rand_int(-3,12);
c = rand_int(-3,12);
printf("%i %i %i\n", a, b, c);
sort3(&a, &b, &c);
printf("%i %i %i\n", a, b, c);
return 0;
}
最佳答案
如果您不想使用 qsort()
,则不需要 compare()
函数。
您可以像这样重写 sort3()
:
void compare_and_swap(int *a, int *b) {
int t;
if (*a > *b) {
t = *a;
*a = *b;
*b = t;
}
}
void sort3(int *a, int *b, int *c) {
compare_and_swap(a, b);
compare_and_swap(a, c);
compare_and_swap(b, c);
}
这实际上是一个“bubble sort”。
关于排序 3 个随机数的 C 程序,void reorder3(int a, int *b, int **c);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8047761/