C中小数位的计算问题

问题描述

我试图编码灰度并且在计算时遇到问题。谁能解释为什么这会返回 27.00000 而不是 27.66667?

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

int main(void)
{

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

}

解决方法

你忘记投射了:

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