Mohammed Fahad
Mohammed Fahad

Reputation: 29

How to call function in other function c++?

The code works fine but the problem is the calculation. how can I call the Cube function to the SphereVol function so it calculate right?

The formula - if you're wondering - for the volume of a sphere is 4/3 * 3.1416 * radius(cubed)

#include <iostream>
using namespace std;


const float PI = 3.1416;                            

float SphereVol(float num);                        
float Cube(float radius);

void main()
{
   float r,
   radius;

   cout << "Enter a radius: ";
   cin >> radius;

   r = SphereVol(radius);
   cout << "Volume of a sphere with a radius " << radius << " is " << r;


}

float SphereVol(float num)
{
   float r;

   r = ( ( 4 / 3 ) * PI * Cube(num) );   

   return r;
}     

float Cube(float radius)
{
   float num;

   num = ( radius * radius * radius );       

   return num;
}

Upvotes: 2

Views: 122

Answers (1)

taocp
taocp

Reputation: 23624

r = ( ( 4 / 3 ) * PI * Cube(num) ); 

should be

r = ( ( 4.0f / 3.0f ) * PI * Cube(num) ); 

Otherwise, integer division will truncate to 1 instead. Your function calls look OK. You can remove those temporary variables:

float SphereVol(float num)
{
    return (( 4.0f / 3.0f ) * PI * Cube(num));
}  

float Cube(float radius)
{
   return (radius * radius * radius );       
}

Upvotes: 6

Related Questions