C语言 为什么双精度,长双精度总是显示 0 作为输出?



我正在编写代码来查找点(25,40000(与固定点(47,132000(的距离。距离始终打印为 0.0000。 我尝试检查其他组合,给出较小的点值,并使用 %d 打印它们,效果很好。 但是对于 %ld,%lf,%Lf 有些东西不妙。请帮忙。

#include<stdio.h>
#include<math.h>
int main()
{
int x=25,y=40000;  
//printf("Enter x,y");
//scanf(%d %d,&x,&y) 
long double dist;
dist=sqrt((47-x)*(47-x)+(132000-y)*(132000-y));   
printf(" x= %d y=%d dist=%Lfn",x,y,dist);
return 0;
}

整数溢出发生在代码中。下面的代码有效 -

int main()
{
long long int x=25,y=40000;       //int was overflowing and causing you error
long double dist;
dist=sqrt((47-x)*(47-x)+(132000-y)*(132000-y));   //this will safely compute within range and return the desired result
printf("After distancen");
printf(" x= %lld y=%lld dist=%Lfn",x,y,dist);
return 0;
}

您得到的输出错误(-nan当我尝试时(,因为sqrt()中的表达式值溢出并变为负数。(132000-y)*(132000-y)不适合整数范围并给出负值。由于未定义负平方根,因此sqrt()返回nan作为结果。将 y 的类型更改为long long int将解决错误。

希望这有帮助!

最新更新