M
M
Maria2018-01-31 01:38:31
C++ / C#
Maria, 2018-01-31 01:38:31

Why is the result output inf?

Good afternoon! Calculating an arithmetic expression - the sum of a series with a factorial .. If I set the sum of a series up to 6, then everything works, if I set the length of the series n = 6, then in the console pops up instead of the result inf.
Tell me, please, what could be the problem?
ps. factorial is considered correct.. checked. The problem is in the sum of the series.
Here is the code:

using namespace std;

int factorial (int n);

int main()
{
  double sum = 0.0;
  int n, x;
  cout << "Enter n" << endl;
  cin >> n;
  cout << "Enter x" << endl;
  cin >> x;
  for (int i = 1; i <= n; i++) {
    sum += (factorial(2*i) + abs((double)x)) / factorial(i*i);
  }
  cout << "Result is " << sum << endl;
  _getch();
    return 0;
}

int factorial(int n) {
  if (n > 1) {
    return n * (factorial(n - 1));
  }
  else {
    return 1;
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
terrier, 2018-01-31
@terrier

ps. factorial is considered correct.. checked. The problem is in the sum of the series.
Check again, for example, with this example: factorial(36)
Recall that the factorial is a large number, and not so much fits into an int. And what we have there is the result of signed overflow in C ++, remind me?

M
Mercury13, 2018-01-31
@Mercury13

We have an overflow here, 36! does not fit into the int type. Make at least a double.
Inf (“machine infinity”) is usually the result of a fractional division by zero. Why? Let's count how many twos in 36!
Divided by 2 - 18 factors.
And for 4 more - 9 pcs.
And another 8 - 4 pcs.
And for 16 more - 2 pcs.
And another 32 - 1 pc.
Total in the composition of 36! there will be 34 deuces, that is 36! is divisible by 2 34 . Of course, integer arithmetic working in the ring of remainders from division by 2 32 will give zero. In this case, of course, the 32-bit register will repeatedly and hopelessly overflow.
A more complex way to calculate a series is a recursive relation. We divide the next term into two parts: a i= (2i)! / i²! and b i = |x| /i²!. Plot how a i−1 and a i are related , similarly for b.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question