I am new to c++ and i do not know where I go wrong with the following codes.
I am meant to calculate the volume of a sphere with using a function. My function needs to accept radius as its argument and it should return the volume of this sphere. Here is my code;
The volume of a sphere is (4/3) * pi * r^3. Radius is cubed.
Also, 4/3 is integer division. This will give you an answer of 1. The decimal part is truncated. You need to change it to floating point division by making at least one of the numbers (either the 4 or the 3) into a floating point number.
And finally, cout the result in your main function. There is no cout, how is the user supposed to see the answer?
The reason that M_PI* 4/3 * pow( radius, 3 ) works and (4/3*radius*pi) doesn't (aside from the fact that the latter doesn't cube pi) deserves some explanation. Multiplication and division are evaluated from left to right and integers are promoted to double as needed, so the first one is evaluated as: (((M_PI* 4) / 3) * pow( radius, 3 ) ). M_PI is a double, so to multiply M_PI by 4, it has to promote 4 to a double. The result is a double. To divide this result by 3 it has to promote 3 to double first, etc.
In contrast, the second one is (((4/3) * radius ) * pi). This starts by dividing 4 by 3. Since both are integers, it does integer division and gets a result of 1. To multiply this by radius, it promotes 1 to a double. Then it multiplies that result times PI. The compiler will probably optimize this to simply radius*pi.
pow() takes a double as the exponent. Raising a double to a double is fairly complex math, so you should avoid pow() when using small constant integers powers. This would be faster: M_PI * 4 / 3 * radius * radius * radius;