Thread: Function returning incorrect value

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    8

    Function returning incorrect value

    I'm having a little trouble with this block of code:

    Code:
    int sphere()
    {
    	float radius_2, volume;
    
    	printf( "Radius: " );
    	scanf( "%f", &radius_2 );
    	
    	volume = ( 4 / 3 ) * PI * pow( radius_2, 3 );
    	
    	printf( "Volume = %f\n", volume );
    	
    	volume_menu();
    	
    	return 0;
    }
    PI is defined at the beginning of the program as 3.14159 using:

    Code:
    #define PI 3.14159
    My problem is that this function is returning 25.132721 as as volume instead of the correct value of ~33.49. I've narrowed the problem down to the 'volume = ( 4 / 3 ) * PI * pow( radius_2, 3 );' statement; specifically the '( 4 / 3 )' portion of the statement. It seems to me that it is returning 1.0 as 4 / 3 instead of the actual value - even though volume is declared type float.

    Thanks for any help!

  2. #2
    Sr. Software Engineer filker0's Avatar
    Join Date
    Sep 2005
    Location
    West Virginia
    Posts
    235
    You should express it as "(4.0 / 3.0)", or even "(4.0 / 3)" -- that way, you're getting a floating point result rather than an integer result.
    Insert obnoxious but pithy remark here

  3. #3
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Integer division bud.

    4 / 3 = 1
    4 / 3.0 = 1.3333333...

    Also format your floats.

    Code:
    volume = ( 4 / 3.0 ) * PI * pow( radius_2, 3 );
    printf( "Volume = %.3f\n", volume );
    EDIT: Beaten to the punch...
    I guess that's why he's a Senior Software Engineer and I'm... well I'm just a student.
    Last edited by SlyMaelstrom; 12-13-2005 at 01:24 PM.
    Sent from my iPadŽ

  4. #4
    Registered User
    Join Date
    Dec 2005
    Posts
    8
    Thanks a lot guys!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. function returning hour in either 12 or 24 hour format
    By stanlvw in forum C Programming
    Replies: 4
    Last Post: 01-01-2008, 06:02 AM
  2. Problem in returning value from the dll exported function
    By dattaforit in forum Windows Programming
    Replies: 2
    Last Post: 12-04-2006, 04:30 AM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. returning pointers from a function
    By curlious in forum C++ Programming
    Replies: 2
    Last Post: 12-28-2003, 11:37 PM
  5. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM