float data type question

• 04-30-2006
Mark S.
float data type question
I am trying to make a simple program that tests the users ability to divide 2 numbers without a remainder. For some reason even if you type in the the correct answer the program doesnt acknowledge it. The code below should show you what i mean.

Code:

```#include<iostream> using namespace std; int main(void) {         float num1 = 112.0f / 9.0f;                // = 12.4444         float num2 = 12.4444f;         cout << num1 << '\n'                 << num2 << '\n';         if(num1 == num2)                                // why doesnt num1 == num2         {                 cout << "yeah\n";         }                 return(0); }```
how do i make num1 == num2?

Thanks.
• 04-30-2006
SlyMaelstrom
You'd have to understand how floating point arithmetic works. Bottom line is, with various rounding errors that a computer is capable of, you're better of comparing to a de minimus.

Code:

`if(num1 - num2 < .0001 && num1 - num2 > -.0001)`
Someone will probably post a good link that explains the nitty gritty about floating point values and how to use them.
• 04-30-2006
Salem
• 04-30-2006
OnionKnight
Code:

```#include<iostream> using namespace std; int main(void) {         float num1 = 112.0f / 9.0f;                // = 12.4444         float num2 = 12.4444444f;         cout << num1 << '\n'                 << num2 << '\n';         if(num1 == num2)                                // why doesnt num1 == num2         {                 cout << "yeah\n";         }                 return(0); }```
You forgot a few numbers. The first one was 12.4444444 and the other 12.4444000 in your code. However there's another important issue that causes (note: 'causes', not 'can cause') troubles, it didn't in this case but it usually does and the bigger the larger the equation the bigger the chances are.
As it has been pointed out floating-point numbers are approximations so when you compare them you should compare them within a range like Sly did instead of just using the == operator.