w3resource

C#: Value of PI up to n (given number) decimals places

C# Sharp Math: Exercise-19 with Solution

Write a C# Sharp program to find PI value up to n (given number) decimal places.

The number π (/paɪ/) is a mathematical constant. It is defined as the ratio of a circle's circumference to its diameter, and it also has various equivalent definitions. It appears in many formulas in all areas of mathematics and physics. The earliest known use of the Greek letter π to represent the ratio of a circle's circumference to its diameter was by Welsh mathematician William Jones in 1706. It is approximately equal to 3.14159. It has been represented by the Greek letter "π" since the mid-18th century, and is spelled out as "pi". It is also referred to as Archimedes' constant.

Sample Solution:

C# Sharp Code:

using System;
using System.Linq;
namespace exercises
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 2;
            Console.WriteLine("Value of PI up to "+ n + " decimals places -> " + test(n));
            n = 7;
            Console.WriteLine("\nValue of PI up to " + n + " decimals places -> " + test(n));
            n = 15;
            Console.WriteLine("\nValue of PI up to " + n + " decimals places -> " + test(n));

        }
        public static decimal test(int n)
        {
            return decimal.Round(3.1415926535897931m, n);
        }
    }
}

Sample Output:

Value of PI up to 2 decimals places -> 3.14

Value of PI up to 7 decimals places -> 3.1415927

Value of PI up to 15 decimals places -> 3.141592653589793

Flowchart:

Flowchart: C# Sharp Exercises - Value of PI up to n (given number) decimals places.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a C# Sharp program to compute the sum of the positive and negative numbers of an array of integers and display the largest sum.
Next: Write a C# Sharp program to get the Least Common Multiple (LCM) of more than two numbers. Take the numbers from a given array of positive integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.