measuring volume in C++
This is a program I wrote earlier while killing time in the Multilab.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
#include <iostream> using namespace std; const double pi = 3.14159; // I know there is a built-in pi class box { public: double length, width, height; box() {length = 1; width = 2; height = 3;} box(double l, double w, double h) { length = l; width = w; height = h; } double volume() { return length * width * height; } }; class cylinder { public: double length, radius; cylinder() {length = 30.0; radius = 4.5;} cylinder(double l, double r) { length = l; radius = r; } double volume() { return pi * length * (radius * radius); } }; int main() { char choice; bool validChoice; double x, y, z; cout << "Do you want to find the volume of: a) box or b) cylinder? "; choice: cin >> choice; if (choice == 'a') validChoice = true; else if (choice == 'b') validChoice = true; else validChoice = false; if (validChoice == true) { if (choice == 'a') { cout << "Enter a length, width, and height: "; cin >> x >> y >> z; box b1(x, y, z); // It seems kind of awkward to declare this here, // and not at the top of main() cout << "The volume of a box of those proportions is " << b1.volume() << "." << endl; } else if (choice == 'b') { cout << "Enter a length and a radius: "; cin >> x >> y; cylinder c1(x, y); cout << "The volume of a cylinder of those proportions is " << c1.volume() << "." << endl; } } else { while (validChoice == false) { cout << "\nThat is not a valid selection.\n" << "Please choose either a or b for box or cylinder: "; goto choice; } } return 0; } |
comments powered by Disqus