Advertisement
Guest User

Untitled

a guest
Nov 21st, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>      //defines rand(), srand(), RAND_MAX
  3. #include <ctime>        //defines ctime() for random numbers
  4. #include <cmath>        //defines math functions
  5. using namespace std;
  6.  
  7. //calculates the distance of the dart from the origin
  8. double dist(double x, double y)
  9. {
  10.     double throwDist;
  11.     throwDist = sqrt(x*x+y*y);  //Euclidean Distance Formula from point (0,0)
  12.     return throwDist;
  13. }
  14. //calculates pi using number of darts thrown in the circle vs all darts thrown
  15. double pie(int numThrows, double a)
  16. {
  17.     double pieValue = a / numThrows;
  18.     return pieValue;
  19. }
  20. int main()
  21. {
  22.     double coord_x, coord_y, test;
  23.     srand(time(NULL));      //creates the seed time
  24.     test = rand() / double(RAND_MAX);
  25.     double throwDist;       //distance from the origin
  26.     double a = 0;              //times a dart ends up inside the circle
  27.     int numThrows;          //times to throw the dart
  28.     cout<< "Enter how many time to throw the dart: ";
  29.     cin>> numThrows;
  30.  
  31.     //creates 2 random numbers 'n' times
  32.     for(int i = 1; i <= numThrows; i++)
  33.     {
  34.         coord_x = (double)rand() / (RAND_MAX);
  35.         coord_y = (double)rand() / (RAND_MAX);
  36.         throwDist = dist(coord_x, coord_y);
  37.         //counts how often the dart is thrown inside the circle
  38.         if(throwDist <= 1)
  39.         {
  40.             a++;
  41.             double pieCalc = pie(numThrows, a);
  42.              cout<< "The value of PI is: " <<4* pieCalc <<endl;
  43.         }
  44.     }
  45.    
  46. return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement