c - 意外结果,因为浮点减法变为 -0.0 和 +0.0

标签 c floating-point

在下面的代码中,当我输入 0.41 时然后我得到的结果为 4 ,这是预期的,但是当我输入输入 0.15 时然后我得到的结果为 3 ,但它应该是 2 .

我知道原因,因为我的第一个if条件没有变为true,这与 -0.0 和 +0.0 有关。我无法理解这一切是如何发生的。这整个区别在于输入为 0.410.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/

相关文章:

c++ - double 或浮点比较

c - 如何在c中更快地生成正弦函数

c - 为什么双链表中的指针追逐可以避免缓存抖动(自驱逐)?

c - 列出给定大小的单元组的元素的最快方法是什么?

mysql - 我应该使用什么 MYSQL 数据类型来存储 64 位 double ?

java - 按句点将 String 拆分为 String[] 但返回空数组

matlab - 如何在没有除法硬件和浮点硬件的情况下用二进制实现浮点除法

c - 使用 OSX Instruments 7.2 进行时间分析 C 程序

c - 修改指针指向的字符串有效吗?

c++ - 浮点定向舍入和优化