A student in Programming 1 wants to know the surface area and volume of a cylindrical shape.
Figure 5.1: Example of a cylinder
Volume = PI(R^²) x height
Area = 2PI(R^²) x height + 2PI(R^²)
5.1.1 Write a program that will assist the students:
5.1.2Create a C++ source file called Cylinder and save it in a file called Cylinder.cpp.
5.2 Create the following functions:
5.2.1 calcVolume() This function will receive three parameters and it must then calculate
and return the volume of a cylinder using the information given
above.
5.2.2 calcArea() This function will receive three parameters and it must then calculate
and return the area of a cylinder using the information given above.
5.2.3 main() NB: The functions must be implemented above the main.
Add all necessary pre-processor directives.
Declare all constants and necessary variables.
Prompt the user for the height of the cylinder, and the radius of
the base of the cylinder.
Based on the users option :
o Do the relevant calculations by calling the correct
function.
Display the results of the desired measurement.
If an invalid option is selected an appropriate error message
#include <iostream>
#include <cmath>
#define _USE_MATH_DEFINES
using namespace std;
double calcVolume(double height, double radius, double pi) {
double volume;
volume = pi * (radius * radius) * height;
return volume;
}
double calcArea(double height, double radius, double pi) {
double area;
area = 2 * pi * radius * height + 2 * pi * (radius * radius);
return area;
}
int main() {
double height, radius;
double volume, area;
cout << "Enter the height of the cylinder: ";
cin >> height;
if ( height <= 0 ) {
cout << "Error: the height must be a positive number greater than zero";
return 0;
}
cout << "Enter the radius of the base of the cylinder: ";
cin >> radius;
if ( radius <= 0 ) {
cout << "Error: the radius must be a positive number greater than zero";
return 0;
}
volume = calcVolume(height, radius, M_PI);
area = calcArea(height, radius, M_PI);
cout << "\n";
cout << "The volume of the cylinder is " << volume << "\n";
cout << "The area of the cylinder is " << area << "\n";
return 0;
}
Comments
Leave a comment