Search code examples
cheaderstdiosqrt

output of c code


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)