我正在尝试编写一个程序,通过使用指针增加值来对三个 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/