randwalk.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // randwalk.cpp -- using the Vector class
  2. // compile with the vect.cpp file
  3. #include <iostream>
  4. #include <cstdlib> // rand(), srand() prototypes
  5. #include <ctime> // time() prototype
  6. #include "vect.h"
  7. int main()
  8. {
  9. using namespace std;
  10. using VECTOR::Vector;
  11. srand(time(0)); // seed random-number generator
  12. double direction;
  13. Vector step;
  14. Vector result(0.0, 0.0);
  15. unsigned long steps = 0;
  16. double target;
  17. double dstep;
  18. cout << "Enter target distance (q to quit): ";
  19. while (cin >> target)
  20. {
  21. cout << "Enter step length: ";
  22. if (!(cin >> dstep))
  23. break;
  24. while (result.magval() < target)
  25. {
  26. direction = rand() % 360;
  27. step.reset(dstep, direction, POL);
  28. result = result + step;
  29. steps++;
  30. }
  31. cout << "After " << steps << " steps, the subject "
  32. "has the following location:\n";
  33. cout << result << endl;
  34. result.polar_mode();
  35. cout << " or\n" << result << endl;
  36. cout << "Average outward distance per step = "
  37. << result.magval()/steps << endl;
  38. steps = 0;
  39. result.reset(0.0, 0.0);
  40. cout << "Enter target distance (q to quit): ";
  41. }
  42. cout << "Bye!\n";
  43. /* keep window open
  44. cin.clear();
  45. while (cin.get() != '\n')
  46. continue;
  47. cin.get();
  48. */
  49. return 0;
  50. }