I am writing a simple function in c that will return the middle of 2 float values.
My function looks like this:
float mid(float a, float b) {
return (a + b)*0.5;
}
The problem is that this function will always produce 0.000000. I am checking this by using:
printf("%f", mid(2,5))
this will print 0.000000.
However, if i just do:
printf("%f", (2+5)*0.5)
this will print 3.5, which is correct.
How do I fix this problem?
The function is fine. For example, this little snippet outputs correctly.
#include <stdio.h>
#include <string.h>
float mid(float a, float b); //declaration here
int main(void)
{
printf("%f\n", mid(2,5));
return 0;
}
float mid(float a, float b) {
return (a + b)*0.5;
}
The probable problem you have is, you didn't add the declaration of mid() like I did, and the compiler thought it returns implicit int, which causes the problem.
This should work! But I suggest you to pass explicitly double values.
#include <stdio.h>
float mid(float a, float b);
int main() {
printf("%f", mid(2.0, 5.0));
return(0);
}
float mid(float a, float b) {
return (a + b)*0.5;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With