I'm a newbie in C language so I'm still trying to learn the basic concepts. I have a question about a program regarding the median value of 3 numbers. First I wrote the following piece of code:
Code:
#include <stdio.h>
double min(double x, double y){
return x<y ? x : y;
}
double med_aux(double x, double y, double z){
return z<x ? x : min(z,y);
}
double med(double x, double y, double z){
return x<y ? med_aux(x, y, z) : med_aux(y, x, z);
}
int main(){
double n1, n2, n3;
n1=5;
n2=22;
n3=1;
printf("The median of the values is %lf");
printf("%lf", med(n1, n2, n3));
return 0;
}
And it seemed fine to me, but I was getting "The median of the values is 0.0000005.000000" as output, so I changed the printf a bit:
Code:
#include <stdio.h>
double min(double x, double y){
return x<y ? x : y;
}
double med_aux(double x, double y, double z){
return z<x ? x : min(z,y);
}
double med(double x, double y, double z){
return x<y ? med_aux(x, y, z) : med_aux(y, x, z);
}
int main(){
double n1, n2, n3;
n1=5;
n2=22;
n3=1;
printf("The median of the values is %lf", med(n1, n2, n3));
return 0;
}
And I got the desired output, which is "The median of the values is 5.000000". But still, I would like to know why it didn't work the first time, since it seemed correct. Also, if you could better explain the %d(decimal integer) and %f(floating point), when to use which, I would greatly appreciate it. I know these questions may seem trivial but I really want to understand properly. Thank you!!