Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert negative zero to positive zero in C?

Hello I'm learning Objective C and I was doing the classic Calculator example.

Problem is that I'm getting a negative zero when I multiply zero by any negative number, and I put the result into a (double) type!

To see what was going on, I played with the debugger and this is what I got:

(gdb) print -2*0
$1 = 0

(gdb) print (double) -2 * 0
$2 = -0

In the second case when I cast it to a double type, it turns into negative zero! How can I fix that in my application? I need to work with doubles. How can I fix the result so I get a zero when the result should be zero?

like image 954
Guz Avatar asked Mar 11 '12 19:03

Guz


People also ask

Is negative zero the same as positive zero?

Positive numbers are greater than 0 and located to the right of 0 on a number line. Negative numbers are less than 0 and located to the left of 0 on a number line. The number zero is neither positive nor negative. Positive and negative numbers are sometimes called signed numbers.

How do you convert a negative number to a positive number in C++?

to convert this into positive number I used the abs() method as: a = abs(a);

Is zero positive or negative programming?

Zero, 0, is neither positive nor negative.

Is 0 considered positive in programming?

Hence, 0 is neither positive nor negative.


1 Answers

I did a simple test:

double d = (double) -2.0 * 0;

if (d < 0)
    printf("d is less than zero\n");
if (d == 0)
    printf("d is equal to zero\n");
if (d > 0)
    printf("d is greater than zero\n");

printf("d is: %lf\n", d);

It outputs:

d is equal to zero
d is: -0.000000

So, to fix this, you can add a simple if-check to your application:

if (d == 0) d = 0;
like image 108
Richard J. Ross III Avatar answered Sep 23 '22 15:09

Richard J. Ross III