代码之家  ›  专栏  ›  技术社区  ›  Ongky Denny Wijaya

计算球体体积时出错,但公式正确

  •  1
  • Ongky Denny Wijaya  · 技术社区  · 7 年前

    我想计算球体的表面积和体积,但球体的体积不正确。如果输入r=3,则V=84.8229980469,而不是V=113.0973358154,尽管球体体积公式是正确的。请帮帮我。这是我的密码。

    #include<iostream>
    #include<conio.h>
    #include<stdio.h>
    #include<math.h>
    using namespace std;
    float surface_area_of_sphere(float r)
    {
        float L;
        L=4*3.14159265359*r*r;
        return L;
    }
    
    float volume_of_sphere(float r, float &V)
    {
        V=4/3*3.14159265359*r*r*r;
    }
    
    int main()
    {
        float radius,volume,area;
        cout<<"Please input radius of sphere r = ";
        cin>>radius;
        cout<<"==================================="<<endl;
        volume_of_sphere(radius,volume);
        cout<<"Volume of sphere = ";
        printf("%10.10f\n",volume);
        area=surface_area_of_sphere(radius);
        cout<<"Surface area of sphere = ";
        printf("%10.10f",area);
        getch();
    }
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   Aganju    7 年前

    在计算中使用4和3,它们是整数,所以数学是用整数来完成的。在整数运算中,4/3=1。

    在所有地方使用4.0和3.0,它就会起作用。

        2
  •  1
  •   seccpur    7 年前

    如@Aganju建议使用:

    L = 4.0 * 3.14159265359*r*r; 
    

    和功能 volume_of_sphere() 不应返回值。

    void volume_of_sphere(double r, double &V)
    {
        V = 4.0 / 3.0 * 3.14159265359*r*r*r;
    }
    

    此外,对于pi=3.14159265359分辨率, 全部替换 float 数据类型依据 double 以获得所需的精度。