Search code examples
c#mathformulavolume

Not getting correct volume of sphere


this is my code

double inputrad = Convert.ToDouble(Console.ReadLine());
double circlevolume = 4/3 * Math.Pow(circlerad, 3) * Math.PI;

The volume of a circle with radius 2.5 is 65, but i am getting 49. Why?


Solution

  • You need to write something like 4/3.0 or 4.0/3 or 4/3d etc.. otherwise you are using integer division 4/3 which will give exactly 1.

    You can also, as suggested by Dmitry Bychenko, change the order of operations to get a floating point result before applying division:

    4 * Math.PI / 3 * Math.Pow(circlerad, 3).

    The point is, integer divided by integer is integer division, and you absolutely need to avoid this.

    For further information, you can see this Q&A here: Why does integer division in C# return an integer and not a float?