Reputation: 121
My code is as follows:
#include <stdio.h>
#include <math.h>
int distance(int x1, int y1, int x2, int y2){
double value = sqrt(pow((double)(x2- x1),2.0) + pow((double)(y2 - y1),2.0));
return value;
}
int main(void){
int A_x, A_y, B_x, B_y, C_x, C_y;
printf("Enter 1st point:");
scanf("%d", &A_x);
scanf("%d", &A_y);
printf("Enter 2nd point:");
scanf("%d", &B_x);
scanf("%d", &B_y);
printf("Enter 3rd point:");
scanf("%d", &C_x);
scanf("%d", &C_y);
double AB = distance(A_x, A_y, B_x, B_y);
printf("%.2lf", AB);
// double powered = pow((double)(A_x- B_x),2.0) + pow((double)(A_y - B_y),2.0);
// double squared = sqrt(powered);
// printf("%.2lf", squared);
double BC = distance(B_x, B_y, C_x, C_y);
printf("%.2lf", BC);
double CA = distance(C_x, C_y, A_x, A_y);
printf("%.2lf", CA);
if(AB+BC>CA && AB+CA>BC && BC+CA>AB){
double perimeter = AB+BC+CA;
printf("Perimeter of triangle = %.2lf",perimeter);
return 0;
}else{
printf("Invalid traingle");
return -1;
}
}
I am getting the following in the compiler:
I am not exactly sure why I'm getting 2.00 for AB instead of 2.83. Would be glad if someone could explain where I went wrong :)
Upvotes: 0
Views: 199
Reputation: 450
The function distance returns an integer, therefore it truncates the result of the sqrt. You should change the declaration of:
int distance(int x1, int y1, int x2, int y2)
to
double distance(int x1, int y1, int x2, int y2)
Upvotes: 5