int division to float

This is a discussion on int division to float within the C++ Programming forums, part of the General Programming Boards category; This should be a fairly easy question. I have two int variables I need to divide to get a float. ...

  1. #1
    Registered User
    Join Date
    Apr 2008
    Location
    New York
    Posts
    9

    int division to float

    This should be a fairly easy question.

    I have two int variables I need to divide to get a float.
    Code:
    int a=6;
    int b=4;
    float c=a/b;

    This code keeps giving me 1, and I need 1.5.

  2. #2
    Unregistered User Yarin's Avatar
    Join Date
    Jul 2007
    Posts
    1,605
    Code:
    int a=6;
    int b=4;
    float c=float(a)/float(b);
    A class that doesn't overload all operators just isn't finished yet. -- SmugCeePlusPlusWeenie
    A year spent in artificial intelligence is enough to make one believe in God. -- Alan J. Perlis

  3. #3
    Registered User
    Join Date
    Apr 2008
    Location
    New York
    Posts
    9
    nifty

    thanks

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Yarin View Post
    Code:
    int a=6;
    int b=4;
    float c=float(a)/float(b);
    Technically, it's sufficient to cast one side to float, e.g.:
    Code:
    float c=float(a)/b;
    The rules in C and C++ is that if one side is floating point, the other side is converted to float by default.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Quote Originally Posted by rimig88 View Post
    This should be a fairly easy question.
    Indeed. Do people not buy C++ books anymore?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. memory leak
    By aruna1 in forum C++ Programming
    Replies: 3
    Last Post: 08-17-2008, 10:28 PM
  3. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  4. Replies: 2
    Last Post: 03-24-2006, 07:36 PM
  5. My graphics library
    By stupid_mutt in forum C Programming
    Replies: 3
    Last Post: 11-26-2001, 05:05 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21