Home >Backend Development >C#.Net Tutorial >How to type π in C#
Output π in C
#In C#, there are the following methods to output π:
1. Use the built-in Math.PI constant
The Math.PI constant stores the approximate value of π, which is approximately 3.141592653589793. To use it, just write this in your code:
<code class="csharp">Console.WriteLine(Math.PI);</code>
2. Use Math.Atan2(1, 0)
Math.Atan2(y, x) The function returns the angle (in radians) formed by y and x. When y is 1 and x is 0, we get π/2. By multiplying the result by 2, we can get π:
<code class="csharp">Console.WriteLine(2 * Math.Atan2(1, 0));</code>
3. Using a Loop Approximation
We can use a loop to approximate the value of π. The following code uses Machen's formula to calculate an approximation of π:
<code class="csharp">double pi = 0; for (int i = 0; i < 100000; i++) { pi += Math.Pow(-1, i) / (2 * i + 1); } Console.WriteLine(pi * 4);</code>
4. Using the System.Numerics namespace
.NET 5 and above includes System. The Numerics namespace provides a BigInteger type specifically designed to represent numbers of arbitrary precision:
<code class="csharp">using System.Numerics; BigInteger piApprox = BigInteger.Atan2(BigInteger.One, BigInteger.Zero) * 2; Console.WriteLine(piApprox.ToString());</code>
Which method you choose depends on the required precision and performance requirements. For most cases, using Math.PI constants is sufficient.
The above is the detailed content of How to type π in C#. For more information, please follow other related articles on the PHP Chinese website!