Thread: int or double?

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    17

    int or double?

    Hi

    There's something bothering me with my code, and I'm not sure what variable type to use as a result. I have this in my code:

    Code:
    double x;
    int y;
    int z;
    
    x = y/z
    My question is, will x be a double or an integer?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >My question is, will x be a double or an integer?
    x will be a double, but the value will lack any fractional part because y / z uses integer arithmetic. To get the fractional part, use C++'s type conversion rules and cast one of the operands to double:
    Code:
    x = static_cast<double> ( y ) / z;
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Nov 2003
    Posts
    17
    I've seen different syntax somewhere - will this work as well: (float) y?

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > will this work as well: (float) y?
    That's a 'C' style cast, which C++ supports for the moment.
    The static cast Prelude showed is the preferred way for C++
    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.

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >will this work as well: (float) y?
    It will, but since you're assigning to a double variable, (double)y would be better. Or you could cast z instead of y, or both. It really doesn't matter since if either operand is double, the result of the expression is double. Also see Salem's comment on C-style casting.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. NEED HELP READING FILE and PRINTING
    By geoffr0 in forum C Programming
    Replies: 4
    Last Post: 04-16-2009, 05:26 PM
  2. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  3. Conversion From C++ To C
    By dicon in forum C++ Programming
    Replies: 2
    Last Post: 06-10-2007, 02:54 PM
  4. Game Won't Compile
    By jothesmo in forum C++ Programming
    Replies: 2
    Last Post: 04-01-2006, 04:24 PM
  5. Replies: 2
    Last Post: 03-24-2006, 08:36 PM