Thread: adding floating point numbers

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    5

    adding floating point numbers

    Hello all,

    I'm trying to add two numbers, one is seconds and the other is nanoseconds (both in float), but when I do, my results don't come out correctly.
    Can anyone help?

    (I tried to expand the code out so that it can be easily examined)

    Code:
    float endingnano = (float)final.tv_nsec/1000000000;
    
    float endingsec = final.tv_sec;
    
    printf("Ending Nanoseconds = %f\n", endingnano);
    
    printf("Ending Seconds = %f\n", endingsec);
    
    float endingTime = endingnano + endingsec;
    printf("Ending Time = %f\n", endingTime);
    Results:
    Ending Nanoseconds = 0.324691
    Ending Seconds = 1318214528.000000
    Ending Time = 1318214528.000000

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    To get the right answer you have to covert them to the same base... either convert endingnano to seconds or convert your endingsec to nanoseconds before adding... basic math.

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    5
    I thought by dividing nanoseconds by 1000000000 i was converting it to seconds.

    Why can't I add 1234.000000 and 0.123456 and get 1234.123456?

  4. #4
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Location
    Melbourne, Australia
    Posts
    426
    It may be that the float type hasn't got enough significant figures. Try changing all your floats to doubles and see if that helps.
    Code:
    while(!asleep) {
       sheep++;
    }

  5. #5
    Registered User
    Join Date
    Oct 2011
    Posts
    5
    That idea definitely works!

    Thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. floating point numbers
    By MK27 in forum C Programming
    Replies: 2
    Last Post: 07-14-2008, 06:39 PM
  2. Floating-Point Numbers
    By MindLess in forum C Programming
    Replies: 4
    Last Post: 06-24-2007, 11:45 PM
  3. Floating point numbers
    By noor_mirza in forum C++ Programming
    Replies: 3
    Last Post: 10-23-2002, 03:40 AM
  4. Floating point numbers
    By bulsquare in forum C Programming
    Replies: 2
    Last Post: 04-10-2002, 04:44 AM
  5. Adding largest floating point nos
    By sri_dhiraj in forum C Programming
    Replies: 4
    Last Post: 03-28-2002, 06:35 PM