C++ 从球体的体积C+中求出直径+;

C++ 从球体的体积C+中求出直径+;,c++,C++,我的任务是创建一个程序,计算体积为1234.67立方米的球体的直径 我编写了以下代码:- #include <iostream> #include <math.h> using namespace std; int main(){ float vol, dm, h; vol = 1234.67; cout << "Calculating the diameter of sphere with volume 1234.67 cu me

我的任务是创建一个程序,计算体积为1234.67立方米的球体的直径

我编写了以下代码:-

#include <iostream>
#include <math.h>

using namespace std;

int main(){
    float vol, dm, h;
    vol = 1234.67;
    cout << "Calculating the diameter of sphere with volume 1234.67 cu meters" << endl;
    h = vol*(3/4)*(7/22);
    dm = 2 * cbrt(h);
    cout << "The diameter of sphere with volume 1234.67 cu meters is " << dm << endl;
    return 0;
}

这是因为
7/22
等于零。了解C的整数除法

如果要使用浮点精度,则需要使用浮点除法

h = vol*(3/4)*(7/22);
dm = 2 * cbrt(h);

3、4、7、22和2是整数。将它们更改为浮动或双精度(例如3.0或3.f)。这应该可以解决您的问题。

您在任何地方都使用了整数除法,它忽略了浮点部分而不是舍入部分

改用3.f/4.f或3.0/4.0

h = vol * (3 / 4) * (7 / 22);
应该是

h = vol * (3.f / 4.f) * (7.f / 22.f);

int
3/4==0

一样,在提出新问题之前,尝试搜索现有答案。谢谢
h = vol * (3.f / 4.f) * (7.f / 22.f);