Why am I always getting 0 always after running my c program? Kindly help me out

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

     float distance(float a,float b,float c,float d);


      int main()

      {
    float x1,y1,x2,y2,dist;
    printf("Input x1: ");
    scanf("%f", &x1);
     printf("Input y1: ");
      scanf("%f", &y1);
          printf("Input x2: ");
      scanf("%f", &x2);
       printf("Input y2: ");
      scanf("%f", &y2);
       distance(x1,x2,y1,y2);
      printf("Distance between the given points is: %.2f",sqrt(dist));

     return 0;
      }
    float distance(float a,float b,float c,float d)
   {
    float x1,x2,y1,y2,dist;
   dist=((x2-x1)*(x2-x1) +(y2-y1)*(y2-y1));
  return dist;
    }

Here the output is always 0, don't know why. I have tried putting float and integers still getting 0.

IGNORE THIS PART OF QUESTION. WRITING THIS TO SATISFY THE CRITERIA TO POST.

3 Answers

You need to use the return value of the function call

distance(x1,x2,y1,y2);

That is you need to write

dist = distance(x1,x2,y1,y2);

Otherwise the variable dist will be still uninitialized and using it in this statement

printf("Distance between the given points is: %.2f",sqrt(dist));

results in undefined behavior.

The function distance does not use its arguments a, b, c, d. Instead it uses its uninitialized local variables x1, x2, y1, y2

    float distance(float a,float b,float c,float d)
   {
    float x1,x2,y1,y2,dist;
   dist=((x2-x1)*(x2-x1) +(y2-y1)*(y2-y1));
  return dist;
    }

Write the function at least like

    float distance( float a, float b, float c, float d )
    {
        return ( b - a ) * ( b - a ) + ( d - c ) * ( d - c );
    }
`x1,x2,y1,y2` and `dist` not initialized that was the problem :)

#include<stdio.h>
         #include<math.h>
#define _CRT_SECURE_NO_WARNINGS
    
         float distance(float a,float b,float c,float d);
    
    
          int main()
    
          {
        float x1,y1,x2,y2,dist;
        printf("Input x1: ");
        scanf("%f", &x1);
         printf("Input y1: ");
          scanf("%f", &y1);
              printf("Input x2: ");
          scanf("%f", &x2);
           printf("Input y2: ");
          scanf("%f", &y2);
           dist=distance(x1,x2,y1,y2);//you didn't put the value of the func into a variable
          printf("Distance between the given points is: %.2f",sqrt(dist));
    
         return 0;
          }
        float distance(float a,float b,float c,float d)//since we already give a,b,c,d a value from calling the func in main
       {
        float dist;
       dist=((b-a)*(b-a) +(d-c)*(d-c));//we just swapped you x1,x2,y1,y2 to the a,b,c,d 
      return dist;
        }

change your function(it does not use its arguments) to :

  '''float distance(float a,float b,float c,float d)
   {
    float dist;
   dist=((a-b)*(a-b) +(c-d)*(c-d));
  return dist;
    }'''

and in your code :

  printf("Distance between the given points is: %.2f",sqrt(distance(x1,x2,y1,y2)));

 
Related