Advertisement
jyoung12387

Exercise - Find Pi to the nth digit

Feb 18th, 2020
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. using System;
  2.  
  3. namespace random
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             //Define vars
  10.             const double PI = Math.PI;
  11.             int places = 0;
  12.             bool isInt = false;
  13.  
  14.             Console.Write("PI: Enter number of digits to display, between 1-14: ");
  15.  
  16.             do
  17.             {
  18.                 //Get user input
  19.                 string placesAsString = Console.ReadLine();
  20.  
  21.                 try
  22.                 {
  23.                     places = int.Parse(placesAsString);
  24.  
  25.                     if (places < 0)
  26.                     {
  27.                         places = 0;
  28.                         Console.WriteLine("Cannot use a negative value. Decimal places set to 0.");
  29.                         Console.WriteLine("PI at {0} decimal places: {1}", places, Math.Round(PI, places));
  30.                         isInt = true;
  31.                     }
  32.                     else if (places > 14)
  33.                     {
  34.                         places = 14;
  35.                         Console.WriteLine("Cannot use a value over 14. Decimal places set to 14.");
  36.                         Console.WriteLine("PI at {0} decimal places: {1}", places, Math.Round(PI, places));
  37.                         isInt = true;
  38.                     }
  39.                     else
  40.                         Console.WriteLine("PI at {0} decimal places: {1}", places, Math.Round(PI, places));
  41.                         isInt = true;
  42.                 }
  43.                 catch
  44.                 {
  45.                     Console.WriteLine("Please enter a valid number");
  46.                 }
  47.             } while (!isInt);
  48.             Console.ReadLine();
  49.         }
  50.  
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement