Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.20 KB | None | 0 0
  1. using System;
  2.  
  3. namespace FindPi
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             double pi = 4; //Create the variable for Pi and set its start value to 4.
  10.             int denominator = 3; //The variable for the denominator in the Pi formula.
  11.             int counter = 3; //Where are we in Pi.
  12.             int termNumber = 2; //Keep track of the term number to display to the user.
  13.  
  14.             ///Next chunk of code asks the user how many terms they want.
  15.             Console.WriteLine("Please enter the number of terms:");
  16.             string termsNumberString = Console.ReadLine();
  17.             int termsNumber;
  18.             termsNumber = Convert.ToInt32(termsNumberString);
  19.             termsNumber = termsNumber * 2;
  20.  
  21.             ///Display the table headers.
  22.             string titleCol1 = ("Term");
  23.             string titleCol2 = ("Pi");
  24.             string formatTitleTable = "{0,-15} {1,-10}";
  25.             Console.WriteLine(formatTitleTable, titleCol1, titleCol2);
  26.  
  27.             ///Displaying the first term. This is done maually rather than using the formula because it's a starting point.  
  28.             string term1Col1 = ("1");
  29.             string term1Col2 = ("4.0000000000000000");
  30.             string formatTerm1Table = "{0,-15} {1,-10}";
  31.             Console.WriteLine(formatTerm1Table, term1Col1, term1Col2);
  32.  
  33.             ///Figuring out the term value for Pi.
  34.             while (denominator <= termsNumber)
  35.             {
  36.                 if (counter % 2 != 0)
  37.                 {
  38.                     pi -= Convert.ToDouble(4) / denominator;
  39.                     counter++;
  40.                 }
  41.                 else
  42.                 {
  43.                     pi += Convert.ToDouble(4) / denominator;
  44.                     counter++;
  45.                 }
  46.                 denominator += 2;
  47.  
  48.                 ///Displaying the term number and the value of Pi to the user in a table format.
  49.                 string col1 = ("" + termNumber);
  50.                 termNumber++;
  51.                 string col2 = ("" + pi);
  52.                 string formatTable = "{0,-15} {1,-10}";
  53.                 Console.WriteLine(formatTable, col1, col2);
  54.             }
  55.  
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement