Thread: stupid question about converting floats to long ints...

  1. #1
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,212

    stupid question about converting floats to long ints...

    When I compile the program below, it throws up warnings about this statement:
    Code:
      loopspersec = lps / spd;
    because I'm trying to assign a Long Int from a Float.

    My question:
    Is there any function to convert a float to an integer?

    Code:
    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    #include <limits.h>
    #include <math.h>
    
    #define TOTAL_LOOPS 500000000
    
    int main (void)
    {
      clock_t s, e;
      float spd, dur;
      long loopspersec;
      long lps;
      
      if( TOTAL_LOOPS > LONG_MAX)
      {
       printf("Hmmm, this shouldn't happen.");
       return -1;
      }
      
      s = clock();  
      for (lps = 0; lps < TOTAL_LOOPS; lps++ );
      e = clock();
     
      dur = e - s;
      spd = dur / CLOCKS_PER_SEC;
      loopspersec = lps / spd;
      
      printf ( "%ld Loops in %f seconds.\n", lps, spd );
      printf ( "%ld Loops per second.\n", loopspersec);
      system("PAUSE");
      return 0;
    }

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    The warning is about a loss of precision when you convert a float to a long. To remove this warning, you can cast the result of the division to long.

    >loopspersec = lps / spd;
    loopspersec = (long)(lps / spd);

    Though a better method would be to use float for loopspersec. That way you can simply ignore everything past the decimal and you have the added advantage of being able to hold larger values.

    -Prelude
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,212
    Just what I needed, thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem in Converting Unsigned long to String
    By cprogrammer_18 in forum C Programming
    Replies: 8
    Last Post: 01-14-2006, 08:57 AM
  2. Dev-cpp - compiler options
    By tretton in forum C Programming
    Replies: 7
    Last Post: 01-06-2006, 06:20 PM
  3. converting double to long int
    By gunshipolitico in forum C++ Programming
    Replies: 5
    Last Post: 11-07-2005, 10:26 AM
  4. stupid, stupid question
    By xelitex in forum C++ Programming
    Replies: 5
    Last Post: 12-22-2004, 08:22 PM
  5. stupid question???
    By stevey in forum C Programming
    Replies: 9
    Last Post: 11-15-2001, 03:27 PM