I am trying to calculate the volume of a sphere given the radius as a user input. Pi is defined as a constant in my program, and I am using the pow function.
For some reason, I get different results when I switch the order of the 4/3 and the PI. Here is some code to further explain:
const double PI = 3.141593;
int main()
{
double radius;
double volume;
cout << "Enter the radius of a sphere, and the volume will be given." << endl;
cin >> radius;
volume = 4 / 3 * PI * (pow(radius, 3));
cout << "The volume of a sphere with radius " << radius << " is " << volume << endl;
}
The correct answer is only displayed when the constant is placed at the beginning of the expression. For example, when 3 is entered as the radius, the answer is 84.823. But when that expression is displayed like this:
volume = PI * 4 / 3 * (pow(radius, 3));
the answer is 113.097. What is the reason for this?