Home > front end >  How to round in functions
How to round in functions

Time:11-17

void isRight(float sideA, float sideB, float sideC){
float aSquared = sideA * sideA;
float bSquared = sideB * sideB;
float cSquared = sideC * sideC;
round(aSquared);
round(bSquared);
round(cSquared);

if (aSquared   bSquared == cSquared || cSquared   bSquared == aSquared || aSquared   cSquared == bSquared){
    cout << "This is a right triangle" << endl;
}
}
int main() {
float sideA, sideB, sideC;

cout << "Enter the lengths of the three sides of a triangle -- ";
cin >> sideA >> sideB >> sideC;    

    
    isRight(sideA,sideB,sideC);
   
}

}

I have this program that checks side of my triangle and say if it s a right triangle.it works when I have whole numbers like 3 5 4 it gives me the message that it is a right triangle. But if put 1 1.4142 1, it does not give me the message, which is weird because the 1,4142 squared is equal to 2 which is the same of 1 and 1. can someone catch why this is happening. I am guessing its because its not rounding up but I have the round function

CodePudding user response:

This is happening because of Floaing point precision loss.

C built-in floating point types are finite in precision. double is usually implemented as IEEE-754 double precision, meaning it has 53 bits of mantissa (the "value") precision, 11 bits of exponent precision, and 1 sign bit.

To solve this, you can do the following instead of ==:

bool approximatelyEqual(float a, float b, float epsilon)
{
    return fabs(a - b) <= ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}

bool definitelyGreaterThan(float a, float b, float epsilon)
{
    return (a - b) > ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}

bool definitelyLessThan(float a, float b, float epsilon)
{
    return (b - a) > ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}

Note: here, epsilon is the floating point error tolerance value (e.g. 0.000001, 0.0000001 etc)

You can read What Every Programmer Should Know About Floating-Point Arithmetic for more information on floating point formats and their inaccuracies,

  •  Tags:  
  • c
  • Related