开发者

sqrt() returning INF

Hi I'm trying to do some calculations with long doubles and I am getting INF from sqrt(开发者_如何学编程) function.

Code:

#include <math.h>
#include <stdio.h>

int main()
{
    long double bigNUMBER;
    long double p1,p2,p3;
    long double p4;

    p1 = 4.769547e+155;
    p2 = 1.012994e+170;
    p3 = 1.714812e+169;

    p4 = p1*p1 + p2*p2 + p3*p3;

    bigNUMBER = sqrt(p4);

    printf("product: %Lf\n\n", p4); // 1055562645989439942507809393771156765931135...

    printf("\n result %Lf\n\n", bigNUMBER); // INF

    return 0;
}

Thank you!


sqrt takes and returns a double. When you call it, your long double will be converted in a double which cannot store such a big number, and will thus get the value of infinity.

Use sqrtl that takes and returns a long double.


sqrt will return INFINITY when the argument is INFINITY as well; e.g.:

#include <stdio.h>
#include <math.h>
int main()
{
  printf("%g %g\n", INFINITY, sqrt(INFINITY));
  return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜