Function returning incorrect value

This is a discussion on Function returning incorrect value within the C Programming forums, part of the General Programming Boards category; I'm having a little trouble with this block of code: Code: int sphere() { float radius_2, volume; printf( "Radius: " ...

  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,062
    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 12: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, 05: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, 03:30 AM
  3. Replies: 3
    Last Post: 03-04-2005, 01:46 PM
  4. returning pointers from a function
    By curlious in forum C++ Programming
    Replies: 2
    Last Post: 12-28-2003, 10:37 PM
  5. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 06:18 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21