Search code examples
cdoublelong-double

Why double, long double are always showing 0 as output?


I am writing code to find the distance of a point(25,40000) from a fixed point(47,132000). The distance always printed to be 0.0000. I have tried checking other combinations, giving smaller values of points, and printing them with %d, it works great. But with %ld,%lf,%Lf something is not fine. Kindly help.

#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=%Lf\n",x,y,dist);
   return 0;
}

Solution

  • Integer overflow takes place in your code. The below code works -

    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 distance\n");
       printf(" x= %lld y=%lld dist=%Lf\n",x,y,dist);
       return 0;
    }
    

    You were getting wrong output(-nan when I tried out ) because the expression value inside sqrt() was overflowing and becoming negative. (132000-y)*(132000-y) won't fit in an integer range and give negative value. Since, negative square root is not defined, sqrt() returned nan as the result. Changing the type of y to long long int will solve the error.

    Hope this helps !