S
saneman
I have a function:
int F(double a)
{
if (a = =1.0)
{
return 22;
}
return 44;
}
When I call F(1.0) it returns 22. But if I call F from a loop like:
double a = 0.0;
for (int j = 0; j <= 1000; j++)
{
std::cout << F(a) <<std::endl;
a = a + 0.001;
}
It returns 44 instead when 'a' reaches 1 instead of 22!
After a few hours of messing with my brains I found a website where they say
that comparing floats in C++ is not guranteed to return an expected result.
Instead something like this should be used:
if (fabs(result - expectedResult) < 0.00001)
But before I rewrite all my code that compare floats I would like to hear if
anyone has any better suggestion.
int F(double a)
{
if (a = =1.0)
{
return 22;
}
return 44;
}
When I call F(1.0) it returns 22. But if I call F from a loop like:
double a = 0.0;
for (int j = 0; j <= 1000; j++)
{
std::cout << F(a) <<std::endl;
a = a + 0.001;
}
It returns 44 instead when 'a' reaches 1 instead of 22!
After a few hours of messing with my brains I found a website where they say
that comparing floats in C++ is not guranteed to return an expected result.
Instead something like this should be used:
if (fabs(result - expectedResult) < 0.00001)
But before I rewrite all my code that compare floats I would like to hear if
anyone has any better suggestion.