Search code examples
c++classfloating-point-conversion

Faulty Function in C++


Currently I have a function in an application which takes in a float as a parameter and should perform a simple multiplication and division on the value passed in. Before the value is passed into the function in the application, it is typecast to a float as the particulars of the main application deal with the numerical data in ints. Unfortunately when I pass in the value of 0.0 to the function, it does not generate an output of 1.0 (which it should from the calculation the function performs) but merely outputs a value of 0.0 and I was wondering why the calulation was failing to produce the correct output as the program compiles and the calculation is correct as far as I'm aware.

Here is the code:

void CarPositionClass::centre(float inputPos)
{
    if ((inputPos <= 0) && (inputPos >= -125))
    {
        membershipC = ((inputPos + 125)*(1 / 125));
    }
}

It should also be noted that membershipC is a float variable that is a member of the CarPositionClass.


Solution

  • Change 1 / 125 to, say, 1.0 / 125. 1 / 125 uses integer division, so the result is 0.

    Or change this expression

    ((inputPos + 125)*(1 / 125))
    

    to

    (inputPos + 125) / 125
    

    Since inputPos is floating point, so is inputPos + 125, and then dividing a float by an integer is a float.

    P.S. This is surely a duplicate question. I expect the C++ gurus to lower the dup hammer any second now. :)