1

I'm new to C++, and I'm having trouble figuring out where my issue is. I'm trying to ask the user for how far they want to find pi using the Gregory - Leibniz series, but whenever I put any number I always get 4 (1 from the loop). Thanks in advance :)

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main()
{
double x = 0;
double doubleTerms = 0;
cout << "How many terms of pi do you want?" << endl;
cin >> doubleTerms;

cout << "Thanks the amount of terms you want for pi is: " << doubleTerms << endl;
//n is the value for where each number is
//z is to change the number into a negative
//x is to add up into the total value
for(int n = 0; n < doubleTerms; n++)
{
    double z = 1 / (2 * n + 1);

    if((n % 2) == 1)
    {
        z = z * -1;
    }

    x = (x + z);
}
double finalValue = 4 * x;
cout << "The number is: " << finalValue << endl;


system("pause");
return 0;
}
Hubert Jo
  • 31
  • 3
  • You can check this out concerning your divisions: http://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division-in-c – Hayt Sep 16 '16 at 07:18
  • as a suggestion, you may consider using a more efficient yet very simple series, the Nilakantha series. – adrian Nov 23 '17 at 01:48

1 Answers1

3

1 / (2 * n + 1); will be performed in integer arithmetic, so any fraction part is truncated.

One fix is to write 1.0 / (2 * n + 1); instead: then that term will be evaluated in floating point due to the rules of type promotion.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483