Search code examples
cfunctionfloating-pointreturn-valueinteger-arithmetic

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, the f function is supposed to give me 7.5 but instead I have 7 as output.

How can I solve this?


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);