Question about mixed data types- with division

This is a discussion on Question about mixed data types- with division within the C++ Programming forums, part of the General Programming Boards category; Question about the expressions below: Code: cout << 17 / 3.0 << endl; cout << 12.0 / 6 << endl; ...

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    39

    Question about mixed data types- with division

    Question about the expressions below:

    Code:
    cout << 17 / 3.0 << endl;
    cout << 12.0 / 6 << endl;
    5.66667
    2

    I realize about / and integer but why do I get an double result for the first expression and an integer result for the second...I was thinking about promotion of data types...but now I am confused..

    Insight appreciated...

  2. #2
    Registered User
    Join Date
    Oct 2006
    Posts
    2,289
    the result of an arithmetic operation is always the widest of all the data types in the operation, so double / char returns a double. long long / float returns float because float has the greater precision, even though long long is actually larger in bit count.

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    2,692
    What makes you suspect that you are getting an integer result? If you want the decimal point to show for "whole" numbers you must tell the system to display the decimal point for all values. See ios::showpoint().

    Jim

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,293
    12 divided by 6 came out to a whole number, that's all. I doesn't print the double result as 2.0 because you didn't ask it to, so it just picked the shortest way of representing the answer as a string.
    If you do:
    Code:
    cout << 17.0 / 3 << endl;
    you'll see the same as the first line you had above.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  5. #5
    Registered User
    Join Date
    May 2009
    Posts
    39
    Thank you all got what I needed...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question about gcc and data types
    By mramazing in forum C Programming
    Replies: 4
    Last Post: 12-04-2009, 05:51 PM
  2. Question about data types and basic arithmatic
    By hellogamesmaste in forum C Programming
    Replies: 5
    Last Post: 08-08-2009, 06:51 AM
  3. starters question about handling data types.
    By epidemic in forum C++ Programming
    Replies: 14
    Last Post: 07-21-2008, 07:44 PM
  4. Basic question involving data types
    By FingerPrint in forum C++ Programming
    Replies: 1
    Last Post: 10-30-2006, 09:19 PM
  5. Replies: 11
    Last Post: 08-20-2005, 05:50 AM

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