C++ Volume of a Cylinder
#include <iostream>
using namespace std;
const double PI = 3.14159;
double calculateCylinderVolume(double radius, double height) {
return PI radius radius * height;
}
int main() {
double radius, height;
cout << "Enter the radius of the cylinder: ";
cin >> radius;
cout << "Enter the height of the cylinder: ";
cin >> height;
double volume = calculateCylinderVolume(radius, height);
cout << "The volume of the cylinder is: " << volume << endl;
return 0;
}
Explanation:
- #include <iostream>
: Includes the input/output stream library for handling input and output operations.
- using namespace std;
: Declares that we are using the standard namespace to simplify access to its elements like cout
, cin
, etc.
- const double PI = 3.14159;
: Defines a constant variable PI
to store the value of pi, which is approximately 3.14159.
- double calculateCylinderVolume(double radius, double height)
: Function declaration to calculate the volume of a cylinder. It takes the radius and height of the cylinder as parameters and returns the calculated volume.
- return PI radius radius * height;
: Formula for calculating the volume of a cylinder using the formula V = πr²h, where PI
is the constant for pi, radius
is the radius of the cylinder, and height
is the height of the cylinder.
- int main()
: The starting point of the program execution.
- double radius, height;
: Declaration of variables radius
and height
to store user input for the radius and height of the cylinder.
- cout << "Enter the radius of the cylinder: ";
: Outputs a message asking the user to input the radius of the cylinder.
- cin >> radius;
: Takes the user input for the radius and stores it in the variable radius
.
- cout << "Enter the height of the cylinder: ";
: Outputs a message asking the user to input the height of the cylinder.
- cin >> height;
: Takes the user input for the height and stores it in the variable height
.
- double volume = calculateCylinderVolume(radius, height);
: Calls the calculateCylinderVolume
function with the provided radius
and height
values, storing the calculated volume in the volume
variable.
- cout << "The volume of the cylinder is: " << volume << endl;
: Outputs the calculated volume of the cylinder to the console.