Calculating Volume and Surface Area of a Sphere

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stdafx.h"
#define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
using namespace 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?
This is what I did
 
volume = (4 * M_PI * radius *radius *radius)/3


That fixed the problem for me.
but i will try it your way!
Thank you for the help!
Yes, your method will work too. The key is to avoid the integer division of 4/3.
Topic archived. No new replies allowed.