简体   繁体   English

C打印中的sqrt函数-nan

[英]sqrt function in C prints -nan

While doing some code excercise, I observed unusual ouput caused by the sqrt funtion, 在执行一些代码练习时,我观察到由sqrt函数引起的异常输出,

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. 看一下数字: b是4, l是5。所以b*b - l*l是-9。 What's the square root of -9? -9的平方根是多少? It's an imaginary number, but sqrt doesn't support imaginary results, so the result is nan (not a number). 这是一个虚数,但sqrt不支持虚数结果,因此结果为nan(不是数字)。 It's a domain error. 这是域错误。 The solution: Don't pass negative arguments to sqrt . 解决方案:不要将否定参数传递给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. b设为4并将l设为5会产生-ve数,这很可能是您不想要的。

FWIW, root of a negative number needs imaginary part to be represented. FWIW,负数的根需要虚部表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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