0

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.

Bob Gilmore
  • 12,608
  • 13
  • 46
  • 53
Vuk Bibic
  • 1,375
  • 2
  • 10
  • 10
  • 2
    @RawN the C standard functions are also present in C++, and the question includes a `namespace` directive that isn't legal C. Please don't jump to conclusions. – Mark Ransom Jan 11 '17 at 20:16
  • 1
    P.S. although the `-0.00000` was probably caused by a value that is close to but not quite 0, the floating point format allows both +0.0 and -0.0 values. – Mark Ransom Jan 11 '17 at 20:20
  • @MarkRansom I stand corrected. –  Jan 11 '17 at 20:40
  • If you tweaked your input values such that `k=2.5` instead of `k=2.4`, then your answer would come out exactly correct. `k=2.4` is where the math starts to suffer from inexactness of floating point values to store decimal values, specifically, 0.4 or 4/10s is not representable in base 2. 0.5 or 5/10 or 1/2 is exactly representable in base 2. – Mark Lakata Jan 11 '17 at 22:36
  • @MarkLakata I'm submiting this to an online judge, therefore I can't change the test case. The given test case is the only one that I can't pass. Do you think it would work with doubles instead of floats? If yes, could you tell me why I'm not able to print a double using printf? – Vuk Bibic Jan 12 '17 at 12:42
  • @MarkLakata I figuterd it out, I should read in doubles with %lf, but print them with %f. – Vuk Bibic Jan 12 '17 at 13:56

0 Answers0