Compute Volume = (4.0/3.0)PIr³
In this step, you will learn how to calculate the volume of a sphere using the mathematical formula V = (4.0/3.0) _ π _ r³. We'll modify the previous program to include the volume calculation.
Open the existing file and update the code:
cd ~/project
nano sphere_volume.c
Replace the previous code with the following:
#include <stdio.h>
#include <math.h>
int main() {
// Declare variables
double radius, volume;
// Constant for PI
const double PI = 3.14159265358979323846;
// Prompt the user to enter the radius
printf("Enter the radius of the sphere: ");
// Read the radius from user input
scanf("%lf", &radius);
// Calculate the volume using the sphere volume formula
volume = (4.0 / 3.0) * PI * pow(radius, 3);
// Print the radius and calculated volume
printf("Radius: %.2f\n", radius);
printf("Volume of the sphere: %.2f\n", volume);
return 0;
}
Compile the updated program:
gcc sphere_volume.c -o sphere_volume -lm
Example output:
labex@ubuntu:~/project$ gcc sphere_volume.c -o sphere_volume -lm
Note the -lm
flag, which links the math library needed for the pow()
function.
Run the program:
./sphere_volume
Example output:
Enter the radius of the sphere: 5.5
Radius: 5.50
Volume of the sphere: 696.46
Let's break down the key changes:
- Added
#include <math.h>
to use the pow()
function
- Defined a constant
PI
for precise calculations
- Used the formula
volume = (4.0 / 3.0) * PI * pow(radius, 3)
pow(radius, 3)
calculates r³
- Printed both radius and calculated volume