hey guys i am a newbie, can anyone please tell me how to compare decimals in c. i know you can compare integers but decimals??
thanks
|
Mentor
|
![]() |
| 20May2011,12:08 | #2 |
|
Exactly the same way you compare integers:
Code:
float a=3.141, b=2.718; if (a==b) // do something. So floating point comparisons need to take this inaccuracy into account, e.g.: Code:
int a=3.141, b=2.718; if (a-b<0.005 || b-a<0.005) // then assume it matches. |
|
Contributor
|
|
| 10Jun2011,13:40 | #3 |
|
hey thanks a lot,
but i found a way around it just simply by multiply the decimal by a few thousands provided the decimal is ending.e.g compare 2.562715 and 2.562716 then i would multiply buy 1000000 then assign it to 2 integers then compare. i am just a newbie. Thanks for your method please keep in touch. thanks |
|
Mentor
|
![]() |
| 10Jun2011,15:30 | #4 |
|
Yep, that's another way.
Code:
if *(int)(a*1000)==(int)(b*1000)) // then it matches |
|
Mentor
|
![]() |
| 10Jun2011,15:34 | #5 |
|
2147483647 isn't some random number I just pulled out of the air by the way, it's the most you can store in a signed 32-bit int. 2^31-1=2147483647.
And just in case you're thinking overflow might not be too bad, well, 2147483647+2=-2147483647. Stick that up a maths major if you like watching them run away screaming. |

