为什么即使我正确使用了 float 数据类型和说明符,float 值也会给我 0 值

Why float value is giving me 0 value even though i have used float datatype and specifier correctly

我正在编写阶乘和求和的代码,然后将它们相加。我的输出没有给出正确答案。当我 运行 代码时未显示否定答案。

代码是:

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

float f1(int num1);
int f2(int num2);

int main()
{
    int n;
    printf("Enter n: ");
    scanf("%d",&n);

    float y = f1(n)+f2(n);

    printf("Value of y is: %3f",y);

    return 0;
}

float f1(int num1)
{
    int fact = 1;
    int n1 = num1+1;

    for(int i=1 ;i<=n1; i++)
    {
        fact = fact*i;
    }
    printf("factorial = %d \n", fact );

    int f0 = pow(-1,num1);
    printf("pow = %d \n", f0 );

    float f1 = f0/fact ;
    printf("f1 = %f \n", f1 );

    return f1;

}

int f2(int num2)
{
    int sum = 0;

    for(int j=0;j<=4;j++)
    {
        sum = sum + 2*num2;
    }
    printf("f2 = %d \n", sum );
    return sum;
}

我的输出图片是这样的: output

您提到的问题在这一行:

float f1 = f0 / fact;

因为 f0fact 都是 int 结果是 int 即使你把它分配给 float.

您可以通过转换其中一个操作数来解决此问题:

float f1 = (float)f0 / fact;

ISO/IEC 9899:2017 §6.5.5 6 个州:

When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.105) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a [...]

105) This is often called "truncation toward zero".