The surface area calculation is calculating right but my volume is off for some reason. Can someone help me figure out what I am doing wrong.
Input = 2;
Output for Volume = 25.1327 ( Shouldn't this be 33.51032)
Output for Surface Area = 50.2655
#include "stdafx.h"
#define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
char ans = 'y';
while (ans == 'y' || ans == 'Y')
{
double surfaceArea, volume, radius;
cout << "Type in the radius of the sphere to calculate the volume and surface area. " << endl;
cin >> radius;
volume = 4 / 3 * M_PI * radius * radius * radius;
surfaceArea = 4 * M_PI * radius * radius;
cout << "The volume of the ball is " << volume << ". The surface area of the ball is " << surfaceArea << "." << endl;
cout << "Would you like to run this program again? Type (y/n)" << endl;
cin >> ans;
}
return 0;
}
Line 15. Multiplication and division group left to right so this is evaluated as (((((4/3)*M_PI)*radius)*radius)*radius)
The first expression (4/3) involves two integers, so the result is an integer (1).
The next expression is 1*M_PI. M_PI is a double, so 1 gets promoted to a double and then multiplied. The rest of the arithmetic is all done as doubles.
So the fix is to get 4/3 evaluated as a double. You can do this by making one them a double: volume = 4.0 / 3 * M_PI * radius * radius * radius;
Once you have this working, consider an optimization to show that you're awesome: notice that all of the calculations for the surface area are reused when calculating the volume. So why not calculate the surface area first, and then compute the volume in terms of the surface area?