Garrett Smith
Garrett Smith

Reputation: 97

Why does multiplying 0 by negative double make it become -0?

cout << 0 * -5 << endl; // this is zero
cout << 0 * -5.0 << endl; // this is negative zero

I'm new to c++, and I don't understand why multiplying by a double would affect zero times anything since it should always be zero.

Upvotes: 0

Views: 325

Answers (2)

jcarpenter2
jcarpenter2

Reputation: 5458

In the first line,

cout << 0 * -5 << endl;

both 0 and -5 are signed integers. Integers do not distinguish between 0 and -0.

In the second line,

cout << 0 * -5.0 << endl;

the second number is a double, so the 0 gets promoted to a double as well, for which IEEE floating point defines both 0 and -0 values.

Upvotes: 2

OmG
OmG

Reputation: 18838

It comes from the difference between computation of integers and doubles. First expression is done between two integers, but the second one is between two floating point numbers.

Upvotes: 1

Related Questions