Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Float function does not return float value

I have programmed two simple functions. I want the user to write a integer value and the program finds the outputs from these two functions. Here’s how the code looks like,

#include<stdio.h>

float f(int x){
    
    return ((x * (x-2)) / 2);   
}

float g(int x){
    
    return (x * (x - 1) * (x - 2) / 3);
}

int main(){
    
    int i;
    float f0, g0;
    
    scanf("%d", &i);
    
    f0 = f(i);
    g0 = g(i);
    
    printf("f(%d) = %0.2f , g(%d) = %0.2f", i, f0, i, g0);
    
    return 0;
}

I have created float functions but when I enter 5, f function is supposed to give me 7.5 but instead I have 7 as output.

How can I solve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the both these expressions in the return statements

return ((x * (x-2)) / 2);   
return (x * (x - 1) * (x - 2) / 3);

there is used the integer arithmetic.

Change these statements like for example

return ((x * (x-2)) / 2.0f);   
return (x * (x - 1) * (x - 2) / 3.0f);

or

return (( ( float )x * (x-2)) / 2);   
return (( float )x * (x - 1) * (x - 2) / 3);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading