0

I am writing a code for factorial and summation and then adding them together. My output is not giving correct answer. The negative answer is not being shown when i run the code.

Code is:

#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;
}

My output picture is this: output

anastaciu
  • 23,467
  • 7
  • 28
  • 53
Hania Salman
  • 21
  • 1
  • 8

1 Answers1

2

The problem you refer to is in this line:

float f1 = f0 / fact;

As both f0 and fact are int the result is int even if you assign it to float.

You can solve this by casting one of the operands:

float f1 = (float)f0 / fact;

ISO/IEC 9899:2017 §6.5.5 6 states:

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".

Community
  • 1
  • 1
anastaciu
  • 23,467
  • 7
  • 28
  • 53