Problem 1173: Calculate the Volume of a Sphere
Time Limit: 2s Memory Limit: 192MB
Problem Description
Calculate the volume of a sphere based on the given radius.
Input Format
Input consists of multiple groups, each group occupies one line, and each line includes a real number representing the radius of the sphere.
Output Format
Output the corresponding volume of the sphere. For each group of input data, output one line, and the result should be rounded to three decimal places.
Sample Input
1
1.5
Sample Output
4.189
14.137
Code
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const double PI = 3.1415926; // Define Pi
int main() { double r;
// Multiple inputs while (cin >> r) { // Calculate the volume of the sphere: V = (4/3) * π * r³ double volume = (4.0 / 3.0) * PI * pow(r, 3);
// Output the result, rounded to three decimal places cout << fixed << setprecision(3) << volume << endl; }
return 0;
}
Output Result
Code Explanation
-
Define Pi
-
<span>const double PI = 3.1415926</span>: Define the constant for Pi
Multiple Input Handling
-
Use
<span>while (cin >> r)</span>to read multiple radius data
Volume Calculation
-
<span>(4.0 / 3.0)</span>: Note to use floating-point numbers to avoid integer division -
<span>pow(r, 3)</span>: Calculate the cube of the radius -
Complete formula: $\frac{4}{3} \pi r^3$
Formatted Output
-
<span>fixed</span>: Fixed decimal format -
<span>setprecision(3)</span>: Keep three decimal places
Principle Introduction
Volume Formula of a Sphere
The volume formula of a sphere is:

Where:
-
$V$ is the volume of the sphere
-
$r$ is the radius of the sphere
-
$\pi$ is Pi (approximately 3.1415926)
Example Verification
Example 1: r = 1
-
Volume = $\frac{4}{3} \times \pi \times 1^3 = \frac{4}{3} \times 3.1415926 ≈ 4.189$
Example 2: r = 1.5
-
Volume = $\frac{4}{3} \times \pi \times (1.5)^3 = \frac{4}{3} \times 3.1415926 \times 3.375 ≈ 14.137$
The output results are completely consistent with the examples.
Notes
-
Use Floating-Point Division:
<span>4.0/3.0</span>instead of<span>4/3</span>to avoid integer division resulting in 1 -
Precision Requirements: The problem requires three decimal places, use
<span>setprecision(3)</span> -
Multiple Inputs: Use
<span>while (cin >> r)</span>to handle multiple test data

C++ Basic Tutorial Collection
C++ Basic Materials
1. C++ Output
2. C++ Variables
3. C++ Input
4. C++ Expressions
5. IF Statements
6. IF Applications
7. WHILE Loops
8. FOR Loops
9. Arrays
10. One-Dimensional Arrays
11. Two-Dimensional Arrays
12. C++ Functions
13. C++ File Operations – Writing Files
If you find it interesting, please click on me



