If I type 0.01 or 0.02 the the program just exits immediately. What do I do?
#include
char line[100];
float amount;
int main()
{
printf(\"E
What is the most effective way for float and double comparison?
You should use something like this
bool isEqual(double a, double b)
{
return fabs(a - b) < EPSILON;
}
or this
#define ISEQUAL(a,b) ( fabs((a) - (b)) < EPSILON)
and define EPSILON
#define EPSILON (0.000001)
Firstly, do not attempt to compare double
s, or to compare float
s, or to compare double
s to float
s (exception: comparing against 0 is OK, and arguably all integers). Other answers have given good links as to why, but I especially liked: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
Secondly, if you are dealing with an amount of money, don't use double
s, or get out of double
as quickly as possible. Either use a fixed point library (a bit complex for what you want), or simply do:
int cents = (int)round(amount * 100);
then work with cents
instead. You can compare these to your heart's content.
Thirdly, if the idea here is to work out change in quarters, dimes, nickels and pennies, a collection of if
statements is not the way to go, unless you like long and inefficient programs. You will need to do that programatically. And that will be far easier if you have the integer number of cents
above (hint: look at the %
operator).
Declare your comparative value as a float.
if (amount == 0.01f)
printf("Quarters: 0\nDimes: 0\nNickels: 0\nPennies: 1");
Note that you could encounter some undefined behavior by directly testing float equality if you made some calculations with your float variable.
I think we could scale for a factor and make a relative comparison like this:
#define EPSILON (0.000001)
if (fabs(a - b) <= EPSILON * fmax(fabs(a), fabs(b))) {
}
which is more robust than an absolute comparison:
if (fabs(a - b) <= EPSILON ) {
// ...
}
which maybe scale dependent. By the way having the optimum scale depends also from the function, we shouldn't use the same formula for a log and for a sin.