"double type" query in c++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ashjas
    New Member
    • Nov 2007
    • 3

    "double type" query in c++

    Hi,

    in c++ following code produces output as 1 how if i am using d as double?

    double d=9/7;
    cout<<"\n"<<d;

    when i changed d=9/7 to d=9.0/7.0 it showed correct answer with all decimals..

    Is it a rule that for using double we have to assign it a value that has a decimal otherwise it would consider it as an int?

    Thanks.
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    The value 7 is an integer. 7.0 is a decimal number, and thus would be treated as a float/double. To get division to work properly, you have to be careful to use the proper format.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      9/7 is integer division. 7 divides into 9 once. Hence 1.

      You assign the 1 to a double. This forces a conversion from int to double so your see 1.0.

      by using 9.0/7.0 you define the values as double. Then you assign to a double.

      Symbolic constants, like 9.0, are double. If you assign one of these to float (which is smaller), you will get a truncation and possible loss of data warning.

      To assign to a float define your constant as a float: 9.0f ot 9.0F.

      Comment

      Working...