在下面的代码中,当我输入 0.41
时然后我得到的结果为 4
,这是预期的,但是当我输入输入 0.15
时然后我得到的结果为 3
,但它应该是 2
.
我知道原因,因为我的第一个if
条件没有变为true,这与 -0.0 和 +0.0 有关。我无法理解这一切是如何发生的。这整个区别在于输入为 0.41
和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);
}
}
最佳答案
在数出便士时,计数
失败。
例如:
} else {
f1 = f1 - 0.01;
count++; // count pennies
}
关于c - 意外结果,因为浮点减法变为 -0.0 和 +0.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34500379/