Mamen Mamen - 1 year ago 78
C Question

compare 2 values in c always return false

i make a simple program to prove a right triange , then i'm using

function to multiple the input like ;

if(pow(c,2) == (pow(a,2) + pow(b,2))){

then i entered the value to
a = 3, b = 4, c = 5
, it should be true because
25 == 25

but it returned a false,

but if i change the code to this :

if((c*c) == ((a*a) + (b*b))){

the result is true

nb :
input is a double

any explanation of this error ? thank you

Answer Source

pow(x, y) is normally implemented as exp(y log x). This can go off for even seemingly trivial values of the arguments.

You are seeing the effect of this.

There's no hard and fast rule for dealing with floating point precision issues. Comparing with a tolerance is often mooted as a solution but picking the level of tolerance or the way it ought to be applied is not in itself trivial.

In your case it would be best to compare a * a + b * b with c * c; particularly if these are always integral values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download