How to type π in C#

下次还敢
Release: 2024-04-04 18:21:22
Original
1147 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

Related labels:
c#
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template