1

I am studying logic building with C, I just write a small code about equation. Here is the code:

#include<stdio.h>

int main()
{
    float a,b;

    printf("Find solutions for equation: aX + b = 0\n");
    printf("Input value for a: ");
    scanf("%f", &a);
    printf("Input value for b: ");
    scanf("%f", &b);

    if(a == 0)
    {
        if (b ==0)
        {
            printf("Countless solution.");
        }
        else
        {
            printf("Have no solution.");
        }
    }

    else
    {
        printf("Have one solution: x = %.2f", -b/a);
    }

}

The problem is when I input a=any number, b=0, I have solution is: x= -0.00.

I don't understand why it is x = -0.00 instead of x = 0.00? I have tested cases a==0 && b==0, a==0 && b!=0 and it works fine. I am confusing about this. Can anyone explain to me?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
namdh
  • 73
  • 6

3 Answers3

3

The IEEE standard representation of floating point numbers allows for negative 0. Basically, there is one bit which represents the "sign" of a floating point number. When you flip that bit, the sign is flipped. In your example, when you use the value -b, value used is b with its sign bit flipped. 0 with its sign bit flipped is -0.

Daniel
  • 6,595
  • 9
  • 38
  • 70
  • 2
    Adding a note for OP: C doesn't specify how floating point numbers are represented, but IEEE-754 is used in most machines today. – Yu Hao Jun 29 '15 at 17:07
1

Code is working correctly. Many floating point types support + and - zero.

To avoid -0.0 from printing out, add 0.0

printf("Have one solution: x = %.2f", -b/a + 0.0);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

A simplified overview of the problem is:

The precision of floating point numbers is limited to the number of bits in the float type. So assigning the result of any floating point operation to a variable will give you a very, very close approximation, but not an exact number.

Because of this, the IEEE standard specified that floats use signed representations of zero. While the values are precisely zero, the signed variants can be likened to one-sided limits approaching zero (such that a limit can be precisely zero, but any infinitesimally small value will have a sign).

The C notation "-b" is the same as "-1 * b", so if a is positive and b is a positive signed version of 0 then the result of that operation will be a negative signed version of zero.

cosmicFluke
  • 355
  • 1
  • 10
  • 2
    In this case, though, `b` is exactly 0. In other words, `-0` isn't just a way of saying 0 minus a tiny epsilon. According to IEEE, `-0` is a number in its own right. – Daniel Jun 29 '15 at 17:15
  • Ah, thanks for the clarification. I knew that IEEE had signed representations of zero, but it makes sense that 0 would be an exact number by specification. – cosmicFluke Jun 29 '15 at 17:18