C++ Volume of a Sphere
Sure! Here is an example of how you can calculate the volume of a sphere in C++:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double radius;
double volume;
cout << "Enter the radius of the sphere: ";
cin >> radius;
volume = (4/3.0) M_PI pow(radius, 3);
cout << "The volume of the sphere is: " << volume << endl;
return 0;
}
Explanation:
First, we include the necessary header files:
<iostream>
for input/output operations and<cmath>
for mathematical functions.We declare two variables:
radius
to store the radius of the sphere andvolume
to store the calculated volume.We use
cout
to display a message asking the user to enter the radius of the sphere.We use
cin
to read the radius value entered by the user and store it in theradius
variable.We calculate the volume of the sphere using the formula:
volume = (4/3.0) M_PI pow(radius, 3)
.The expression
(4/3.0)
ensures that the division is performed as a floating-point division, resulting in an accurate volume calculation. If we used(4/3)
instead, it would perform an integer division and the result would be truncated to an integer value.M_PI
is a constant defined in the<cmath>
header file that represents the mathematical constant π (pi).pow(radius, 3)
calculates the cube of the radius.Finally, we use
cout
to display the calculated volume of the sphere.The
return 0
statement is used to indicate that the program has executed successfully and is ready to exit.
That's it! The program calculates and displays the volume of a sphere based on the user-provided radius.