I am currently writing a greedy algorithm, but I have stumbled upon a problem when comparing floats.
I would use code like this:
float f = 0;
if (f == 0) {
// code
}
I have tested this on a seperate program and it worked fine, but not on the program I am working on.
Here is an extract from my own program.
float chf2 = fmod(chf, 0.1);
float ch3 = chf - chf2;
if (chf2 == 0) {
/* Divide user's number by 0.1 */
float ch3 = chf / 0.1;
/* Round the number */
int ch4 = round(ch3);
/* Print the amount of coins and end */
printf("%d\n", ch4 + coin2);
return 0;
}
Oddly, this seems to work with a previous if statement that checks when a fmod of 0.25 from the user's input.
Is there a better way of checking if a float is equal to another float?