c - 如何在 ANSI C 中进行浮点乘法?

标签 c ansi-c

以下代码:

    float numberForFactorial;
    float floatingPart = 1.400000;
    int integralPart = 1;

    numberForFactorial = ((floatingPart) - (float)integralPart) * 10;

    printf("%d", (int)numberForFactorial);

返回 3 而不是 4。您能解释一下原因吗?

最佳答案

最接近1.400000float略小于1.4。您可以通过执行以下操作来验证

printf("%0.8hf\n", floatingPart);

结果来自ideone1.39999998。这意味着小数点后第一位数字的 10 倍是 3

要避免此问题,请使用舍入而不是截断。一种简单的舍入方法是在截断之前添加一半:

printf("%d", (int)(numberForFactorial + 0.5f));

将按照您的预期打印4。您还可以使用roundrintlroundmodf来获得相同的结果:https://www.gnu.org/software/libc/manual/html_node/Rounding-Functions.html 。舍入是一个复杂的主题,因此请选择最适合您的情况的约束方法。

关于c - 如何在 ANSI C 中进行浮点乘法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39235075/

相关文章:

c - 是否可以在没有单独查找表的情况下为一组小的(<64)键创建最小完美哈希函数?

c - 如何在ansi c中打印va_list的内容

c - int var 得到奇怪的值

c - 示例 mq_timedreceive

c - 函数 invertNumerSubstrings 不起作用

c - ANSI C : isprint() returns true for non-ASCII character?

c - 为什么我的 ANSI C 函数不保留它设置的参数值?

c - 为什么argv的第一个参数是1而不是0

c - 使用 getline() 动态分配的具有动态分配的字符串元素的数组

c - 16PIC877A 用 C 代码复位