-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestion2.cpp
More file actions
34 lines (29 loc) · 1009 Bytes
/
question2.cpp
File metadata and controls
34 lines (29 loc) · 1009 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
* Write a program that asks a user to input the radius, then the program calculates the
* volume of a sphere (the formula for the volume is (4/3) πr^3). Use the inbuilt exponential
* function in C++ to compute (r^3).
*/
#include <iostream>
#include <cmath>
using namespace std;
int main() {
// Declaration of variables
double radius, volume;
// Prompt the user to enter the radius of the sphere
cout << "Enter the radius of the sphere: ";
cin >> radius;
if (cin.fail()) {
// Reject strings
cout << "Invalid input! Please enter a number.";
return 1;
} else if (radius < 0) {
// Reject negative values for the radius
cout << "Radius cannot be negative!";
return 1;
} else {
// Calculate and display the volume of the sphere
volume = (4.0/3.0) * M_PI * pow(radius, 3);
cout << "The volume of the sphere with radius " << radius << " is " << volume << " cubic units!\n";
return 0;
}
}