简体   繁体   中英

sqrt function in C prints -nan

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 .

In your case, not validating the inputs cause the issue.

sqrt(b*b-l*l)

with b as 4 and l as 5 produces a -ve number, which is most possibly you don't want.

FWIW, root of a negative number needs imaginary part to be represented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM