In the below code when I enter input as 0.41
then I get result as 4
, which is expected but when I enter input as 0.15
then I get result as 3
, but it should have been 2
.
I know the reason because my very first if
condition is not becoming true, and this has to do with -0.0 and +0.0. I am not able to understand how this all is happening. This whole difference is with input as 0.41
and 0.15
.
#include <stdio.h>
#include <math.h>
void performMath(float);
int count = 0;
int main(void){
printf("Enter dollars\n");
float userInput = FloatInput(); //FloatInput() is just a method to get user input.
float* ptr = malloc(sizeof(float));
float cents = modff(userInput, ptr);
performMath(cents);
}
void performMath(float f1){
printf("performMath : %f\n", f1);
if(f1 <= 0.0){ //It fails in this condition when user input is 0.15.
printf("Change is: %i\n", count);
} else{
if((f1 - 0.25) >= 0.0){
f1 = f1 - 0.25;
count++;
} else if((f1 - 0.10) >= 0.0){
f1 = f1 - 0.10;
count++;
} else if((f1 - 0.05) >= 0.0){
f1 = f1 - 0.05;
count++;
} else { // Even if I user "else if((f1 - 0.01) >= 0.0)" and f1 is 0.01 then also flow doesn't enter this condition.
f1 = f1 - 0.01;
count++;
}
performMath(f1);
}
}