0
#include <iostream>
int main()
{   
    //Returns Seven divided by three is 2
    std::cout << "Seven divided by three is " <<  7/3  << std::endl;

    //Return Seven divided by three is 2.33333
    std::cout << "Seven divided by three is " <<  7.0/3  << std::endl; 
    std::cout << "Seven divided by three is " <<  7.0/3.0  << std::endl;
}

How does adding .0 to the end of a number return a decimal answer even though I have not put a float or double variable in the code?

Syed Husain
  • 135
  • 9

3 Answers3

8

c++ is a strongly typed language. This means every object, even rvalue constants, have a type. 7 and 7.0 differ in type. You can see that in a simple example:

std::cout << typeid(7).name() << "\n";
std::cout << typeid(7.0).name() << "\n";

prints:

i
d

for integer and double.

The reason that your division operations cause a double print in the single case of 7.0/3 is because of the rules of integral promotion. In this case the 3 is promoted to a double and the resulting value is of type double.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
4

The constants 7 and 3 are integer, while the constants 7.0 and 3.0 are double floating points.

When you divide two integers the result is an integer.

When you divide two floating point numbers or a floating point and an integer, the result is a floating point number with the highest precision of each.

Eran
  • 423
  • 4
  • 12
  • Your last sentence is not strictly true. If you had a platform with a very very large `int` (128 bit, or even 64 bit) say, then it would still be converted to a `double`, which could come at a precision cost. With the advent of 64 bit `int`, we are nearly there. – Bathsheba Jun 19 '18 at 13:54
  • 4
    It is not highest precision of each but depends on rules called "integral promotion" - https://en.cppreference.com/w/cpp/language/implicit_conversion – Slava Jun 19 '18 at 14:00
1

Because it makes the operand of type double thus causing the entire expression to be of type double.

When you append a .0 character sequence to something that used to be a integral literal it is no longer an integer. It now represents a floating point literal of type double which is one of the operands in an expression that is of type double so the operator<< chooses a double overload (the fifth one) and outputs the result accordingly.

Expression:

7 / 3

is of type int as both operands are of type int.

Expression of:

7.0 / 3

is of type double as at least one of the operands is of type double.

Expression:

7.0 / 3.0

is also of type double.

Ron
  • 14,674
  • 4
  • 34
  • 47