Thread: Using modf()

  1. #1
    Registered User
    Join Date
    Jan 2020
    Posts
    12

    Using modf()

    Hello,


    I have a variable named: "number".
    My goal is to be left with only the fraction portion of "number".
    This is the code I wrote:


    Code:
    float fraction_number = number - int ( number ) ; // Decrement the integer portion to be left only with the fraction.
    But I understand that C++ has a native function for just that - modf()
    Can you please show how to use modf() to achieve the same result ?

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    Code:
    #include <iostream>
    #include <cmath>
     
    int main() {
        float value = 123.456;
        float whole, part = std::modf(value, &whole);
        std::cout << value << '\n' << whole << '\n' << part << '\n';
    }
    A little inaccuracy saves tons of explanation. - H.H. Munro

  3. #3
    Registered User
    Join Date
    Jan 2020
    Posts
    12
    Thanks John.
    Using modf() (instead of my code) was advocated by Salem in this thread:
    double_to_fixed function and file IO
    Other then modf() being an "of the shelf" function - are there other benefits of using it instead of what I did ?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. modf function doesn't work properly
    By paranoidgnu in forum C Programming
    Replies: 1
    Last Post: 06-29-2011, 09:59 AM
  2. modf function incompatible pointer type
    By thescratchy in forum C Programming
    Replies: 3
    Last Post: 03-18-2010, 07:46 AM
  3. fmod vs. modf vs. floor
    By Epy in forum C Programming
    Replies: 13
    Last Post: 10-04-2009, 08:21 PM
  4. modf() anomalous behaviour
    By John Connor in forum C Programming
    Replies: 4
    Last Post: 02-04-2008, 03:20 PM

Tags for this Thread