【问题标题】:Error in calculate volume of sphere but the formula is correct计算球体体积时出错,但公式正确
【发布时间】:2018-05-05 03:25:03
【问题描述】:

我想计算球的表面积和球的体积,但球的体积不正确。如果我输入 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();
}

【问题讨论】:

  • 4/3 将两个int 文字(43)相除,因此给出int 类型的结果。这发生在向零舍入时,因此给出值1。它位于具有浮点值的表达式中这一事实不会改变表达式第一部分的计算方式。
  • 好的。谢谢你。现在我明白了。

标签: c++ function formula


【解决方案1】:

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

在所有地方都使用 4.0 和 3.0,它会工作。

【讨论】:

【解决方案2】:

正如@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 以获得所需的精度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多