This is a code for pythagorean triplet. Can somebodby explain the working of if
statement below.
int main()
{
int a, b;
float c;
//calculate the another side using Pythagoras Theorem
//a*a b*b = c*c
//c = sqrt(a*a b*b)
//maximum length should be equal to 30
for(a=1;a<=30;a )
{
for(b=1;b<=30;b )
{
c = sqrt(a*a b*b);
if(c == (int)c)
{
printf("(%d, %d, %d)\n",a,b,(int)c);
}
}
}
}
CodePudding user response:
It is checking whether the value is integral. 'c' is a float, the cast drops any fractional part. The original value of 'c' is then checked against the result of that cast. If they match then the original c was an integral value (note that even with this cast there are plenty of integral values that will fail this test, any value of 'c' larger than std::numeric_limits::max())
CodePudding user response:
This if statement does not have to work because floating point (float
, double
, etc) representations in the processor are different from integers (int
, char
, etc). Therefore, in the general case, this kind of operator is erroneous.
Floating-point numbers are sometimes impossible to represent exactly as an integer (especially as a result of some kind of calculation) (see wiki and this question), and integers are always represented exactly.
In your case, one way to make the if statement correct is to write it like this:
if (fabs(c - roundf(c)) < eps) {
...
}
where eps
is required accuracy. For example,
float eps = 1e-12; // 10^(-12)