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:

  1. First, we include the necessary header files: <iostream> for input/output operations and <cmath> for mathematical functions.

  2. We declare two variables: radius to store the radius of the sphere and volume to store the calculated volume.

  3. We use cout to display a message asking the user to enter the radius of the sphere.

  4. We use cin to read the radius value entered by the user and store it in the radius variable.

  5. We calculate the volume of the sphere using the formula: volume = (4/3.0) M_PI pow(radius, 3).

  6. 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.

  7. M_PI is a constant defined in the <cmath> header file that represents the mathematical constant π (pi).
  8. pow(radius, 3) calculates the cube of the radius.

  9. Finally, we use cout to display the calculated volume of the sphere.

  10. 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.