【问题标题】:Calculation issue with decimal places in C [duplicate]C中小数位的计算问题[重复]
【发布时间】:2021-01-16 19:13:31
【问题描述】:

我正在尝试编写灰度代码,但在计算时遇到了问题。谁能解释为什么这会返回 27.00000 而不是 27.66667?

#include <math.h>
#include <stdio.h>

int main(void)
{

    float count = ((27 + 28 + 28) / 3);
    printf("%f\n", count);

}

【问题讨论】:

标签: c floating-point double decimal-point


【解决方案1】:

你忘记投射了:

int main()
{
    float count = ((27 + 28 + 28) / (float)3);
    printf("%f\n", count);

    return 0;
}

或者:

int main()
{
    float count = ((27 + 28 + 28) / 3.0);
    printf("%f\n", count);

    return 0;
}

https://www.tutorialspoint.com/cprogramming/c_type_casting.htm

【讨论】:

  • 谢谢!那行得通。只是为了安全起见:每当我使用硬编码的数字时,它会自动进行整数除法,除非我在数字前添加小数点或 (float)?
  • 这取决于操作数的类型。在两个整数之间,结果将是一个整数。在整数和浮点数之间,结果将是浮点数。
  • @chux-ReinstateMonica 我指的是第一个示例,其中数字被转换为浮点数。提到第二个,你是对的。
  • @MatteoGalletta 你是对的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多