strctptr.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // strctptr.cpp -- functions with pointer to structure arguments
  2. #include <iostream>
  3. #include <cmath>
  4. // structure templates
  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. void rect_to_polar(const rect * pxy, polar * pda);
  17. void show_polar (const polar * pda);
  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)
  25. {
  26. rect_to_polar(&rplace, &pplace); // pass addresses
  27. show_polar(&pplace); // pass address
  28. cout << "Next two numbers (q to quit): ";
  29. }
  30. cout << "Done.\n";
  31. return 0;
  32. }
  33. // show polar coordinates, converting angle to degrees
  34. void show_polar (const polar * pda)
  35. {
  36. using namespace std;
  37. const double Rad_to_deg = 57.29577951;
  38. cout << "distance = " << pda->distance;
  39. cout << ", angle = " << pda->angle * Rad_to_deg;
  40. cout << " degrees\n";
  41. }
  42. // convert rectangular to polar coordinates
  43. void rect_to_polar(const rect * pxy, polar * pda)
  44. {
  45. using namespace std;
  46. pda->distance =
  47. sqrt(pxy->x * pxy->x + pxy->y * pxy->y);
  48. pda->angle = atan2(pxy->y, pxy->x);
  49. }