从球体C ++的体积中找出直径

时间:2015-06-04 14:01:24

标签: 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 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;
}

我的程序出了什么问题,它输出0作为输出

Calculating the diameter of sphere with volume 1234.67 cu meters                                                                                                             
The diameter of sphere with volume 1234.67 cu meters is 0 

4 个答案:

答案 0 :(得分:0)

这是因为word = raw_input("Enter a word: ").lower() s=[list(i) for i in word.split()] s=[x for _list in s for x in _list] print s for i in s: print ord(i)-96 等于零。阅读C&C的整数除法here

如果您打算使用浮点精度,则需要使用浮点除法。

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

你到处都使用了整数除法,它忽略了浮动部分而不是舍入。

使用3.f / 4.f或3.0 / 4.0代替

答案 3 :(得分:0)

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

应该是

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

int 3 / 4 == 0一样。

相关问题