0

Today I got a homework from my university and I had the surprise that I am unable to solve it. It wants me to find the value of the following expression (fibonacci(n) / factorial(n)) using some functions, but in the end it would print 0 no matter what values I type in. The fibo function calculates the nth fibonacci number, the fact function calculates n! and the expression function calculates the value of fibo(n) / fact(n). I declared the expression function as a float because fact > fibo in every case for n > 1.

#include <stdio.h>

int fibo(int n) {
    int a0 = 0, a1 = 1, t;
    for (int i = 2; i <= n; ++i) {
        t = a0 + a1;
        a0 = a1;
        a1 = t;
    }
    return t;
}

int fact(int n) {
    int f = 1;
    if (n <= 1) return f;
    for (int i = 2; i <= n; ++i) {
        f *= i;
    }
    return f;
}

float expression(int n) {
    float exp = fibo(n) / fact(n);
    printf("%f\n", exp);
    return exp;
}

void main () {
    int n;
    
    printf("Type your number: ");
    scanf("%d", &n);

    printf("fibo = %d\n", fibo(n));
    printf("fact = %d\n", fact(n));

    printf("%f", expression(n));

}```
Andrei Radu
  • 109
  • 1
  • 1
  • 9

2 Answers2

2

The right side of an equals is evaluated without regard for the type in the left side, then the type is converted to the left hand side's type. So you need to cast, or the divide will be integer division.

(float)fibo(n) / fact(n);

In more complex expressions, while the inputs of an operator are widened, this does not flow backwards to results of other operators (example: 1.25 + 2 / 3 is still 1.25), so it's not unusual to see two or more casts in an expression.

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • You should not make the OP think that for every operator the right operand is converted to the left operand's type. For example, 1 + 3.0 gives a double. – DarkAtom Nov 01 '20 at 23:50
  • @DarkAtom: Fixed wording. – Joshua Nov 01 '20 at 23:53
  • The real question here is why are you answering something that was already answered 101 times here on SO instead of just voting to close as a duplicate... – Marco Bonelli Nov 02 '20 at 00:10
0

As kol said in a reply, I should have changed float exp = fibo(n) / fact(n); to float exp = 1.0f * fibo(n) / fact(n);

Andrei Radu
  • 109
  • 1
  • 1
  • 9