Calculating Volume Of sphere

Discussion in 'Mac Programming' started by abcdefg12345, Mar 18, 2014.

  1. abcdefg12345 macrumors regular


    Jul 10, 2013
    Im trying to calculate volume of sphere in Xcode where i enter the radius and it gives me the volumes

    volume of sphere formula = (4/3)#r³

    xcode volume of sphere formula I'm using

    - (IBAction)Sphere:(id)sender
        float result = (4/3) * 3.141592653589793 * ([_Sphereradius floatValue] * [_Sphereradius floatValue] * [_Sphereradius floatValue]);
        [_SphereVolume setFloatValue:result];
    i keep getting wrong value for the volume

    if i for example enter 5 to radius field I'm getting 392.699096679688 when i should be getting 523.5987756

    what am i doing wrong
  2. Phil A. Moderator

    Phil A.

    Staff Member

    Apr 2, 2006
    Shropshire, UK
    It looks to me like the (4/3) is being treat as an integer and is rounding down to 1 (if you calculate 1 * 3.141592653589793 * ([_Sphereradius floatValue] * [_Sphereradius floatValue] * [_Sphereradius floatValue] it gives you the error you're getting)


    float result = (4.0/3.0) * 3.141592653589793 * ([_Sphereradius floatValue] * [_Sphereradius floatValue] * [_Sphereradius floatValue]);
  3. abcdefg12345 thread starter macrumors regular


    Jul 10, 2013
    I tried (4.0/3.0) and it worked, u r right it's been treating (4/3) as an integer
  4. Dranix macrumors 6502a


    Feb 26, 2011
    Gelnhausen, Germany
    Yes as is default in all c-based languages. Simply put a "." or ".0" on one of the constants to force the expression to floating point.

    The problem is that the parser treats sub-expressions separated from each other when considering type. So "(4/3)" is a integer expression because both operands are integers. I normally add "." to the first operand so it would look like "(4./3)".
  5. Senor Cuete macrumors regular

    Nov 9, 2011
    The value of pi (and 2pi, etc.) is defined in header file math.h as
    #define M_PI 3.14159265358979323846264338327950288
    so you should #include <math.h> and use M_PI instead of declaring a value for pi.

    On some systems eg. double * double * double is much faster than pow(double, 3.0) so this is sometimes found as an optimization but there is some overhead in fetching your value with the accessor method [_Sphereradius floatValue], so I would just call pow([_Sphereradius floatValue], 3.0) unless you have some reason to do it the way you did.
  6. ArtOfWarfare macrumors G3


    Nov 26, 2007
    More important than the performance hit from calling the accessor method like this is the maintance hit from this. It makes it more difficult to read and more likely that they'll make a mistaken when modifying the code in the future.
  7. Partron22 macrumors 68020


    Apr 13, 2011
    Your 4/3 is giving an integer result 1, instead of the floating val 1.333333.

    392.699... * 1.33333 = 523.5987...

Share This Page