Syed Husain
Syed Husain

Reputation: 135

Why does adding ".0" in C++ arithmetic functions give out the answer in decimal points?

#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?

Upvotes: 0

Views: 1059

Answers (3)

Ron
Ron

Reputation: 15521

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.

Upvotes: 1

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33944

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.

Upvotes: 8

Eran
Eran

Reputation: 547

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.

Upvotes: 4

Related Questions