tags:

views:

310

answers:

3

This is probably an easy one, but is the right way to calculate volume for a sphere in c++. My getArea() seems to be right, but when I call getVolume() it doesn't output the right amount. With a sphere of radius = 1, it gives me the answer of pi, which is incorrect:

double Sphere::getArea() const
{
    return 4 * Shape::pi * pow(getZ(), 2);
}

double Sphere::getVolume() const
{
    return (4 / 3) * Shape::pi * pow(getZ(), 3);
}
+20  A: 

You're using integer division in (4 / 3). Instead, use floating point division: (4.0 / 3.0).

4/3 is 1, because integer division only produces integers. You can confirm this by test code: std::cout << (4/3) << std::endl;.

jemfinch
+1, force float type division.
Robb
+1 Yup, getVolume might as well be (and may even be optimized to) `Shape::pi * pow(getZ(), 3)`.
Nathan Ernst
@Nathan, you meant by the compiler, right? Otherwise the formula would have been horribly inaccurate for calculating volumes.
Xavier Ho
@Xavier, yes I meant optimized by the compiler. ;) Obviously the formula would otherwise be in correct.
Nathan Ernst
+5  A: 

In (4 / 3), these are both integers so you get integer division. That means the result will be truncated (1.333... becomes 1). Make one of them a double so the other gets promoted to a double during division, yielding a correct result.

I prefer to use (4.0 / 3.0).

GMan
+3  A: 

(4 / 3) is an integer expression and is therefore being truncated to 1. Try (4.0 / 3.0)

Steve Fallows