R
R
raspberryjelly2021-11-30 19:37:40
C++ / C#
raspberryjelly, 2021-11-30 19:37:40

Why does the program always output 0? How to fix?

Exercise:
61a65324cf8e3110463516.png

#include <iostream>
using namespace std;
int fibonacci(int n)
{
  if (n == 0)
    return 0;
  else if (n == 1)
    return 1;
  else
    return fibonacci(n - 1) + fibonacci(n - 2);
}
int main()
{
  int x{}, N{};
  double S{};
  cout << "Input x and N: " << endl;
  cin >> x >> N;
  for (int i{ 1 }; i <= N; i++)
  {
    S += ((fibonacci(i)) / (x + fibonacci(i + 1)));
  }
  cout << "S = " << S << endl;
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-11-30
@raspberryjelly

You are dividing two ints where you are counting the formula. In the C++ language, in this case, integer division occurs. Since the numerator is less than the denominator, it always turns out to be 0. Either cast it to double with a static_cast, or change the type somewhere to double (of a function or a variable). Or, at worst, add 0.0 to the numerator or denominator.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question