Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

max function

Status
Not open for further replies.

Maurader

Technical User
Joined
May 8, 2002
Messages
59
Location
CA
is there a function that will return the max of two doubles?

Thanks
 
Floating point comparisons can be tricky. They are handled differently. I would suggest that you choose to what decimal place you want to be accurate to. For example, if I wanted to know if

double a = 1.902456;
double b = 1.902478;

if(a==b)

and I only cared about 3 decimal places here is what I would do.

int val1 = (int)(a*1000);
int val2 = (int)(b*1000);

NOTICE The parens... just make sure you cast appropriately.

then

val1+= ((int)(a*10000))%10 >=5 ? 1:0;
val2+= ((int)(a*10000))%10 >=5 ? 1:0;

return val1 == val2

In this case it will return true;

if b was = to 1.902578, val2 would be rounded up to 1903 and this would return false.


Matt
 
I haven't found one. The easiest way would be to write your own.

double MaxDouble(double num1, double num2)
{
If(num1 > num2)
return num1;
return num2;
}
 
that is pretty sad...hehe
 
Sorry... i returned true or false above...

should be

if(val1<val2)
return val2;
return val1;

Matt
 
oops again... i meant
if(val1<val2)
return a;
return b;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top