2

代码工作正常,但问题在于计算。如何将 Cube 函数调用到 SphereVol 函数以便计算正确?

公式 - 如果你想知道 - 球体的体积是 4/3 * 3.1416 * 半径(立方)

#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;
}
4

1 回答 1

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

应该

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

否则,整数除法将截断为 1。您的函数调用看起来不错。您可以删除这些临时变量:

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

float Cube(float radius)
{
   return (radius * radius * radius );       
}
于 2013-05-07T03:25:04.840 回答