c++visual-c++fmodf

modf does not work properly


This code should display if first 3 digits of fractional part contains "9", but does not work. "mod" variable, surprisingly, is 0 for any number.

int main( void )
{
    float number, dmod;
    int mod;
    double digit_1, digit_2, digit_3;
    double search=9;

    cout<<"Enter the number:";
    cin>>number;

    mod = modf(number, &dmod);
    digit_1 = mod /100 % 10;
    digit_2 = mod /10  % 10;
    digit_3 = mod /1   % 10;

    if( (digit_1 == search) || (digit_2 == search) || (digit_3 ==search) )
    {
        cout<<"mod contains 9"<<endl;
    }
    else
    {
        cout<<"mod does not contains 9"<<endl;
    }
 }

Solution

  • Your problem is that modf returns the fractional part, not an integer representing the fractional part. The value returned is always less than one and then when assigned to an int it gets truncated down to 0.

    Maybe you wanted to multiply the return by 1000: mod = modf(number, &dmod) * 1000.0;