I am trying to calculate (ab)/2, where a and b are floats. I am then printing then with printf("%.5f", (ab)/2). The result I am expecting is 187.50000, but instead I am getting the result of 187.49997. This is my code here.
#include <cstdio>
#include <cmath>
using namespace std;
float ax, ay, bx, by, k, n;
int main()
{
scanf("%f %f %f %f", &ax, &ay, &bx, &by);
if (ay == by || ax == bx) printf("N");
else
{
k = (by - ay)/(bx - ax);
n = ay - k*ax;
if (n == 0) printf("N");
else
{
float a = abs(n);
float b = abs(n/k);
float c = sqrt(a*a+b*b);
printf("%.5f %.5f %d", a+b+c, (a*b)/2, (k > 0 ? (n > 0 ? 2 : 4) : (n > 0 ? 1 : 3)));
}
}
return 0;
}
The input values I am using are:
12.5 -60 25 -90
For this test case, the values for the following variables are:
k = 2.4
n = 30
a = 30
b = 12.5
c = 32.5
(a*b)/2 should obviously equal 187.5, but I still get the result of 187.49997.
I am aware that I should always use doubles instead of floats, but I couldn't get around printing doubles with printf. The %.5lf always seems to output -0.00000. I could use some help with that problem too.