c - 使用指针对 3 个 double 值进行排序

标签 c pointers double temp

我正在尝试编写一个程序,通过使用指针增加值来对三个 double 字进行排序。

我能够打印 double 值;但是,对于大多数订单来说,它们的顺序并不正确。

这就是我所拥有的:

#include <stdio.h>

void sort3(double *x, double *y, double *z);


int main()

{
    double x,y,z;
    printf("Enter three numbers: ");
    scanf("%lf %lf %lf", &x,&y,&z);
    sort3(&x,&y,&z);
        return 0;
}


void sort3(double *x, double *y, double *z)
    { 
    double temp, temp2, temp3, temp4, temp5, temp6, temp7;

    if (y<x && y<z && z>x)     // MSL
    {
       temp = *x;
       *x = *y;
       *y = temp;
       printf("The order sequence is: %.1lf %.1lf %.1lf \n", *x, *y, *z);
      }

    else if (z<x && (x>y) && (y>z)){      // LMS
        temp2 = *z;
      *z = *x;
       *x = temp2;
       printf("The order sequence is: %.1lf %.1lf %.1lf \n", *x, *y, *z);

      }

     else if(z>y && y<x && x>z ) {   // LSM
     temp3 = *z;
      *z = *x;
       *x = temp3;

       temp4 = *x;
       *x = *y;
       *y = temp4;

       printf("The order sequence is: %.1lf %.1lf %.1lf \n", *x, *y, *z);

    }

     else if(z>x && y>z && y>x ) {   // SLM
        temp5 = *z;
       *z = *y;
       *y = temp5;
       printf("The order sequence is: %.1lf %.1lf %.1lf \n", *x, *y, *z);

    }

    else if(x>z && y>z && y>x ){        // MLS

       temp6 = *x;
       *x = *y;
       *y = temp6;

      temp7 = *y;
      *y = *x;
       *x = temp7;
       printf("The order sequence is: %.1lf %.1lf %.1lf \n", *x, *y, *z);


        }   

    else{
       printf("The order sequence is: %.1lf %.1lf %.1lf \n", *x, *y, *z);

    } //SML




  }

我不确定问题出在哪里以及如何以及如何解决它们。

最佳答案

void swap(double *x, double *y){
    double t = *x;
    *x = *y;
    *y = t;
}

void sort3(double *x, double *y, double *z){
    if(*x > *y)
        swap(x, y);
    if(*x > *z)
        swap(x, z);
    if(*y > *z)
        swap(y, z);
    printf("The order sequence is: %.1lf %.1lf %.1lf \n", *x, *y, *z);
}

关于c - 使用指针对 3 个 double 值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21769478/

相关文章:

c# - 使用带小数的指数

c - 新的 C23 #embed 指令的目的是什么?

c - C 中的指针问题

c++ - (C++ 错误 : pointer being freed was not allocated) for linked lists

C# IEEE754 舍入

c++ - atoi 与整数和 double

c - 编程C动态表错误存储大小 `table'未知

c - 用getche输入字符并存入数组

c - 我的程序的代码只能运行一次并且不会循环 - 在代码块上出现错误并崩溃

c++ - CUDA 错误 : too much shared data (0x4018 bytes, 0x4000 最大值): where do the extra 0x18bytes come from?