Reputation: 1
#include <stdio.h>
int main()
{
int x1;
int x2;
int y1;
int y2;
printf("Enter the value of x1 and y1 %d %d ",x1,y1);
scanf("%d %d",&x1,&y1);
printf("Enter the value of x2 and y2 %d %d ",x2,y2);
scanf("%d %d",&x2,&y2);
int l1=x2-x1;
int l2=y2-y1;
int len1=l1*l1;
int len2=l2*l2;
int length=len1+len2;
int lengthf=sqrt(length);
printf("The length between the points = %d",lengthf);
return 0;
}
I was not expecting the locations of the variables. I have to get the distance between two points.
Upvotes: 0
Views: 46
Reputation: 7726
There are several faults in the code:
x1
, y1
, x2
, and y2
are used uninitialized that invokes UB.
You are losing precision to the actual result by casting a double
to an int
.
You are missing math.h
library.
You don't check for the scanf()
values.
Lots of redundant variables.
The code can be rather written this way. Follow the comments to understand.
#include <math.h>
#include <stdio.h>
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
// Storing the coordinate values in a structure.
struct point {
int x;
int y;
};
int main(void)
{
struct point p1 = { 0, 0 };
struct point p2 = { 0, 0 };
fprintf(stdout, "Enter the value of x1 and y1: ");
// Validation of input -- considered good practices.
if (fscanf(stdin, "%d %d", &p1.x, &p1.y) != 2) {
fprintf(stderr, "error: The value(s) are invalid.\n");
return EXIT_FAILURE;
}
fprintf(stdout, "Enter the value of x2 and y2: ");
// Validation of input -- considered good practices.
if (fscanf(stdin, "%d %d", &p2.x, &p2.y) != 2) {
fprintf(stderr, "error: The value(s) are invalid.\n");
return EXIT_FAILURE;
}
// Finally, evaluation of the distance using pow() and sqrt().
double distance = sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2));
fprintf(stdout, "Distance between two points: %.2lf\n", distance);
return EXIT_SUCCESS;
}
Upvotes: 2