[cs13001] comparing integers and doubles

Mikhail Nesterenko mikhail at cs.kent.edu
Wed Jan 30 16:48:05 EST 2013


CSI students,

The question was asked in class whether it is possible to use
relational operators to compare mixed type operands (integers and
doubles).

In C++, the syntactic rules for relational operators are the same as
for arithmetic operators: if one of the operands is a double, the
other operand is converted to double. 

That is, it is syntactically correct to compare integers and
doubles. However, care must be taken when comparing for equality of
this kind:

   int i=2;
   double d=2.0;

   if (i == d)
      cout << "they are equal\n";
   else
      cout << "they are not equal\n";


The reason is that floating point numbers (double) may not be
represented exactly (due to the finiteness of the size of memory
locations and the way floating point numbers are stored). Hence, the
value of a double may be ever so slightly different from the exact
value (say 2.0 may be represented as 1.99999999...) Usually, such
difference is negligible. However, when comparing for equality the
results may be unexpected.


Thanks,
-- 
Mikhail


More information about the cs13001 mailing list