While doing some code excercise, I observed unusual ouput caused by the sqrt funtion,
The code was,
#include<stdio.h>
#include<math.h>
int main()
{
double l,b,min_r,max_r;
int i;
scanf("%lf %lf",&b,&l);
printf("%lf %lf\n",sqrt(l*l+b*b),sqrt(b*b-l*l));
return(0);
}
Output:
4 5
6.403124 -nan
Why does this happenes.
Look at the numbers: b
is 4 and l
is 5. So b*b - l*l
is -9. What's the square root of -9? It's an imaginary number, but sqrt
doesn't support imaginary results, so the result is nan (not a number). It's a domain error. The solution: Don't pass negative arguments to sqrt
.