0

I am trying to write a code that finds pi accurately. When I run my code I get an output of 1.000000 every time because n always equals 0 in the equation to find add and minus after the first equation but when I print it, n is increasing as it should. I don't get any error messages because there are no visible problems with the code that I have. This is a conversion from the same code I wrote in python and I don't know if that is meaning I have forgotten something.

#include <stdio.h>

int main()
{
    int n = 1, iterations, times;
    long double pi = 0.0, add, minus;

    printf("Number of iterations: ");
    scanf("%d", &iterations);
    for (times = 1; times <= iterations; ++times)
    {
        add = 1 / n;
        printf("%Lf \n", add);
        pi = pi + add;
        n = n + 2;
        minus = 1 / n;
        printf("%Lf \n", minus);
        pi = pi - minus;
        n = n + 2;
        printf("%d \n", n);
        printf("%Lf \n", pi);
    }
    pi *= 4;
    printf("Pi = %Lf \n", pi);
    return 0;
}
the busybee
  • 10,755
  • 3
  • 13
  • 30
Joliver
  • 17
  • 3
  • 4
    Replace `add = 1 / n;` with `1.0 / n;` or `(long double)1 / n;` and other similar lines, to get floating point division. – Weather Vane Jun 11 '20 at 13:45
  • This is such an incredible common FAQ and I don't think we have any good canonical duplicate. Anyone? – Lundin Jun 11 '20 at 13:53

1 Answers1

0

Works a treat if you define n as a double.

When n is defined as an integer 'minus = 1 / n;' will always be 0, except when n = 1;

James Anderson
  • 27,109
  • 7
  • 50
  • 78