-3

Why output is giving 3 , expecting -3. How to handle such preprocessing in c?

#include<stdio.h>
#include<math.h>
#define sq(x) ((x<0)?sqrt(-x):sqrt(x))

int main()
{
    int x;
    x=sq(-9);
    printf("%d\n",x);
    return 0;
}
X Slash
  • 4,133
  • 4
  • 27
  • 35
anil
  • 29
  • 6

5 Answers5

4

because your # define "sq" checks if its a negative number and turns it into a positive number before calculating a square root

its doing sqrt(-x) which is sqrt(-(-9)) ( taking the negative of a negative is the positive)

so its doing sqrt(9)

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
1

You have this define:

define sq(x)  ((x<0)?sqrt(-x):sqrt(x))

Since you're passing -9, x<0 is true, so it's doing sqrt(9), which is 3.

You then print the 3.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
1

The code is doing exactly what it's being told, I think.

sq(x) tests first for x < 0 - in your case, this is true, so sq(x) calls sqrt(-(-9)) - which is 3.

An attempted solution is (x < 0) ? -sqrt(-x) : sqrt(x), which will return negative roots for negative x (my best interpretation of your intent).

mzhang
  • 392
  • 3
  • 12
  • but actually preprocessor just replace x with passed value..so sq(-9) should be seem like this ((-9<0)?sqrt(--9):sqrt(9))...and it should be give an error...but u tell it replace like this sqrt(-(-9))...how it is possible – anil Jan 27 '12 at 19:00
  • I believe `-1 * x` will work. (`--9` being `-1 * -9` being passed into `sqrt`) – mzhang Jan 27 '12 at 23:03
1

Wait, wait, wait.

Are we trying to break the basic rules of Math here?

The square root of -9 is 3 i.

That's because (-3)^2 is 9. Negative numbers have 'imaginary' square roots. sqrt(-1) is i. Not -1. (-1)^2 is 1.

ThatOtherPerson
  • 834
  • 6
  • 18
0

If you expect -3, then you probably meant

#define sq(x)  ((x<0)?-sqrt(-x):sqrt(x))

but why would you expect negative square root of negative number is beyond me.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173