Question
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;
}
Solution
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)
OTHER TIPS
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.
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).
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.
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.