3

Please forget me if I my question is not right.I am a beginner in c++. I just wrote a simple program in c++ My code is:

#include<iostream>
using namespace std;
int main()
{
    float a,b,c;
    a=0;
    b=-5;
    c=a/b;
    cout<<c;

}

When I ran this code the output is -0. How the answer could be -0 while -0 doesn't exist?

  • 6
    In floating point numbers, there is a single bit for indicating the sign of the number. Depending on how you do the calculation, that can be set, even when the answer comes out as `0`. – BoBTFish Sep 01 '20 at 10:03
  • 3
    [Signed zero](https://en.wikipedia.org/wiki/Signed_zero). – DevSolar Sep 01 '20 at 10:05
  • 2
    who told you there is no zero negative in the informatic? – ΦXocę 웃 Пepeúpa ツ Sep 01 '20 at 10:05
  • 2
    not a duplicate question, but one example for -0 does actually exist: https://stackoverflow.com/questions/45795397/behaviour-of-negative-zero-0-0-in-comparison-with-positive-zero-0-0/45795465 – 463035818_is_not_an_ai Sep 01 '20 at 10:10
  • One thing you learn as a programmer is that computer representations of numbers only approximate mathematical notions of what a number is. In computing `-0.0` does exist. – john Sep 01 '20 at 10:29
  • @john, I guess you're talking about floating numbers. As on the other number types like int, short,... there is no approximation. – Just Shadow Sep 01 '20 at 10:31
  • @JustShadow I'm certainly talking about floating point numbers, but -0.0 is not an approximation for anything, it's a number in it's own right which is different from +0.0. – john Sep 01 '20 at 10:37
  • Samsil Arefeen `+0.0 == -0.0` is true, but sometimes +0.0 and -0.0 makes a [difference](https://stackoverflow.com/q/25332133/2410359) . – chux - Reinstate Monica Sep 01 '20 at 15:13

2 Answers2

6

How the answer could be -0 while -0 doesn't exist?

Your assumption is wrong. -0 does exist in floating point number representations, and therefore the answer can be -0.

For reference, see the IEEE-754 standard and for "why", see Branch Cuts for Complex Elementary Functions or Much Ado About Nothing's Sign Bit.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

There is a simple logic behind:
Let's assume you're dividing another number to -5, for example, 2.
So if you divide 2 to -5, first it will divide 2 to 5, and then apply the - sign to the result.
The same logic when you use 0 instead of 2. So 0/5 = 0, and applying the - sign, mades it -0.

P.S. As other guys already mentioned in comments, -0 does exist in float universe.
P.P.S. By saying "apply - sign" I mean it just sets the first bit (aka "Sign bit") in the float to 1.
Structure of the float and -0
For more info about the float structure see here.

Just Shadow
  • 10,860
  • 6
  • 57
  • 75