-1

I tried writing a code, which is supposed to calculate 4 - 4/3 + 4/5 - 4/7 + 4/9 +... but it keeps printing "3" as the answer.

#include <iostream>
#include <math.h>
#include <conio.h>

using namespace std;

int main()
{
    int s=0,a,n;
    cin>>n;
    for(int i=0 ; i<=n ; i++)
    {
        a=(4/((2*i)+1))*pow(-1,i);
        s=s+a;
    }
    cout<<s;
    return 0;
}
m.s.
  • 16,063
  • 7
  • 53
  • 88
Sina
  • 19
  • 5

1 Answers1

5

You are using integer division, so your series converges really, really quickly.

Make s and a be doubles, and replace 4 with 4.0.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055