Here's one way to calculate the value of pi in C# using the Leibniz formula:
main.cs129 chars9 lines
This program uses a loop to add up the terms of the Leibniz formula, which alternates between positive and negative values. The denominator increases incrementally by 2 each time to add the next odd integer to the series. After adding up a sufficient number of terms, the value of pi is multiplied by 4 to calculate the final result.
Note that the program does not use the most efficient algorithm for calculating pi, but it is simple to implement and works well for small values of n. There are many other approaches and algorithms for calculating pi more accurately, such as the Gauss-Legendre algorithm, the Monte Carlo method, and the Borwein algorithm.
gistlibby LogSnag