Returning float value when writing a function in C

I am writing a simple function from c that will return the average of two 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 check this using:

printf("%f", mid(2,5))

      

0.000000 will be printed.

However, if I just do:

printf("%f", (2+5)*0.5) 

      

this will print correctly 3.5.

How do I fix this problem?

+3


source to share


2 answers


The function is great. For example, this little snippet is displayed 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 likely problem is that you didn't add a declaration mid()

like I did and the compiler thought it was returning an implicit one int

, which is causing the problem.

+8


source


It should work! But I suggest you pass double values ​​explicitly.



#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; 
}

      

+2


source







All Articles