Thread: int and float - will this work?

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    28

    int and float - will this work?

    I've got this code and I'm trying to multiply something times 1.3 (float value)

    Anyways, P is defined:

    int p=0;

    Here's the code:

    Code:
     for(pos = (minimum+(p*1.3)); pos < (maximum-p); pos += 1)  
      {                                  
        myservo.write(pos);             
        delay(3);                       
      } 
      
      for(pos = (maximum-p); pos>=(minimum+(p*1.3)); pos-=1)  
      {                                
        myservo.write(pos);          
        delay(3);                      
      }
    I'm looking to multiply the int value (non decimal number) times 1.3 as in the above code.

    Will this work? I don't need a float for resolution... just an integer but I'd like to multiply by float values.

    Just unsure of how all of the float and integer values work together.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Yeah, it should work.

    But are you working on some kind of embedded processor lacking floating point hardware?
    In which case, it could be extremely expensive to calculate.

    If you've got the integer head room, you could always do p * 13 / 10
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    If you multiply an int by a float, the int will automatically be converted to a float for you for the multiplication operation. Of course, once you set the float result to your int pos, the decimal portion of the number will be truncated (e.g. 4.3 will become 4, 7.8 will become 7).
    If you understand what you're doing, you're not learning anything.

  4. #4
    Registered User
    Join Date
    Nov 2010
    Posts
    28
    Great thanks guys! And it worked in real life with the hardware I'm working on (Arduino Microcontroller and a servo).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  3. Debug Error Really Quick Question
    By GCNDoug in forum C Programming
    Replies: 1
    Last Post: 04-23-2007, 12:05 PM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM