structfun.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // strctfun.cpp -- functions with a structure argument
  2. #include <iostream>
  3. #include <cmath>
  4. // structure declarations
  5. struct polar
  6. {
  7. double distance; // distance from origin
  8. double angle; // direction from origin
  9. };
  10. struct rect
  11. {
  12. double x; // horizontal distance from origin
  13. double y; // vertical distance from origin
  14. };
  15. // prototypes
  16. polar rect_to_polar(rect xypos);
  17. void show_polar(polar dapos);
  18. int main()
  19. {
  20. using namespace std;
  21. rect rplace;
  22. polar pplace;
  23. cout << "Enter the x and y values: ";
  24. while (cin >> rplace.x >> rplace.y) // slick use of cin
  25. {
  26. pplace = rect_to_polar(rplace);
  27. show_polar(pplace);
  28. cout << "Next two numbers (q to quit): ";
  29. }
  30. cout << "Done.\n";
  31. return 0;
  32. }
  33. // convert rectangular to polar coordinates
  34. polar rect_to_polar(rect xypos)
  35. {
  36. using namespace std;
  37. polar answer;
  38. answer.distance =
  39. sqrt( xypos.x * xypos.x + xypos.y * xypos.y);
  40. answer.angle = atan2(xypos.y, xypos.x);
  41. return answer; // returns a polar structure
  42. }
  43. // show polar coordinates, converting angle to degrees
  44. void show_polar (polar dapos)
  45. {
  46. using namespace std;
  47. const double Rad_to_deg = 57.29577951;
  48. cout << "distance = " << dapos.distance;
  49. cout << ", angle = " << dapos.angle * Rad_to_deg;
  50. cout << " degrees\n";
  51. }