Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning a float value when writing a function in C

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?

like image 802
user3000820 Avatar asked Dec 02 '25 21:12

user3000820


2 Answers

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.

like image 136
Yu Hao Avatar answered Dec 04 '25 10:12

Yu Hao


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; 
}
like image 39
Rizier123 Avatar answered Dec 04 '25 10:12

Rizier123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!