a program that arranges two real numbers in ascending order

Asked 2 years ago, Updated 2 years ago, 34 views

First, a function sort2 for re-storing two real values in *num1, *num2 is created by using a function swapd.After that, after calling sort2, create a program using the results to display it like an example of execution.

I want to write a program like this, but I don't know how to write it.

We exchanged values with the function swapd, and in sort2, we thought we wanted to call it swapd(num1,num2)num2>num1, we wanted to call it swd(num>,num2).

Run Results

$./a.out 
Input n1—15.9
Input n2: 11.1
Before Sorting
n1: 15.900000: n2:11.100000  
After Sorting
n1: 11.100000: n2:12.200000  

source code

 void swapd_double(double*num1, double*num2)
{
    double tmp;
    tmp = * num1;
    *num1 = *num2;
    * num2 = tmp;
}
void sort2 (double*num1, double*num2)
{
    if(num1>num2){
     return swapd_double(num1,num2);
    } else if(num2>num1){
        return swapd_double(num2,num1);
    }
}

double main (void)
{
    double num1, num2;
    printf("Input n1:");
    scanf("%lf", & num1);
    printf("Input n2:");
    scanf("%lf", & num2);

    printf("Before Sorting\nn1:%f, n2:%f\n", num1, num2);
    sort2(&num1,&num2);
    printf("After Sorting\nn1:%f, n2:%f\n", num1, num2);

    return 0;
}

c

2022-09-30 19:50

2 Answers

The results of "replace num1 and num2" and "replace num2 and num1" are the same.Therefore, the code below does the same thing regardless of whether it branches into an if statement.

 if(num1>num2){
    return swapd_double(num1,num2);
} else if(num2>num1){
    return swapd_double(num2,num1);
}

What I want to do now is align it so that num1<=num2.In other words, if num1<=num2 from the beginning, nothing needs to be done.Must be replaced only when num2<num1.Therefore, the code looks like the one below.

 if(num2<num1){
    // Replace num1 and num2 here
}
return


2022-09-30 19:50

The function swapd_double means swapd_double(num1,num2); or swapd_double(num2,num1);, so it always replaces num1 and num2 except when num1 and num2 are the same.


2022-09-30 19:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.