int or double?

This is a discussion on int or double? within the C++ Programming forums, part of the General Programming Boards category; Hi There's something bothering me with my code, and I'm not sure what variable type to use as a result. ...

  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,796
    >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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,417
    > 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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >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, 03:24 PM
  5. Replies: 2
    Last Post: 03-24-2006, 07:36 PM

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