排序 3 个随机数的 C 程序,void reorder3(int a, int *b, int **c);

标签 c sorting pointers random

此代码有效,但它不是我想要的。有谁知道如何在没有 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/

相关文章:

c - 在opencv中获取LAB图像的像素值

c - 自动存储持续时间结构初始化

iOS:对包装 CGPoint 的 NSValue 的 NSArray 进行排序

c++ - 读写文件到数组

c - 如何将一个节点从一个链表添加到另一个链表

c - 为什么 char name[1] 可以容纳 1 个以上的字符?

c - C中删除方阵中的一列和一行

sorting - 在 Elasticsearch 中如何按两个日期中较小的一个进行排序?

c++ - 在C++中按字母顺序将节点添加到链表

c - C 标准是否允许为指针分配任意值并递增它?