Advertisement
Guest User

Untitled

a guest
Jul 25th, 2016
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7. // given the coordinates of a point (x,y) computes if the point is inside the circle
  8. // centered at origin with radius r. Returns 'true' if it is inside, 'false' otherwise.
  9. bool isInside(double x, double y, double r)
  10. {
  11.     return pow(x, 2) + pow(y, 2) <= pow(r, 2);
  12. }
  13.  
  14. // given s, the size of the side of a square that is centered at the origin,
  15. // chooses a random coordinates inside the square, and calls isInside function
  16. // to test if the point is inside the circle or not.
  17. bool throwDart(int s)
  18. {
  19.     int x, y;
  20.     // assign x and y to two random integers between -s/2 and s/2
  21.     x = (rand() % s) - s / 2;
  22.     y = (rand() % s) - s / 2;
  23.  
  24.     //Call the isInside function and return its output.
  25.     return isInside(x, y, s / 2);
  26. }
  27.  
  28. int main()
  29. {
  30.     srand(333);
  31.     float side; // this is the side of the square and is also our resolution.
  32.     float tries;  // this is the number of tries.
  33.  
  34.                 //Ask the user for the size (integer) of a side of the square
  35.  
  36.                 //Get the users input using cin
  37.     cin >> side;
  38.     //Ask the user for the number of tries using cout
  39.  
  40.  
  41.     //Get the users input using cin.
  42.     cin >> tries;
  43.  
  44.     int inCount = 0; //counter to track number of throws that fall inside the circle
  45.  
  46.     for (int i = 0; i < tries; ++i)
  47.     {
  48.         //throw a dart using throwDart method and increment the counter depending on its output.
  49.         if (throwDart(side)) {
  50.             inCount++;
  51.         }
  52.     }
  53.  
  54.     cout << "in count:" << inCount << endl;
  55.     cout << "tries: " << tries << endl;
  56.  
  57.     //Compute and display the estimated value of PI. Make sure you are not using integer division.
  58.     double Pi;
  59.     Pi = 4 * (inCount / tries);
  60.     cout << Pi << endl;
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement