[英]Calculating volume for sphere in C++
This is probably an easy one, but is the right way to calculate volume for a sphere in C++? 这可能很简单,但是在C ++中计算球体积的正确方法是什么? My
getArea()
seems to be right, but when I call getVolume()
it doesn't output the right amount. 我的
getArea()
似乎是正确的,但是当我调用getVolume()
它没有输出正确的数量。 With a sphere of radius = 1
, it gives me the answer of pi
, which is incorrect: 对于
radius = 1
的球体,它给出了pi
的答案,这是不正确的:
double Sphere::getArea() const
{
return 4 * Shape::pi * pow(getZ(), 2);
}
double Sphere::getVolume() const
{
return (4 / 3) * Shape::pi * pow(getZ(), 3);
}
You're using integer division in (4 / 3)
. 你在
(4 / 3)
4/3)中使用整数除法。 Instead, use floating point division: (4.0 / 3.0)
. 相反,使用浮点除法:
(4.0 / 3.0)
。
4/3
is 1, because integer division only produces integers. 4/3
是1,因为整数除法只产生整数。 You can confirm this by test code: std::cout << (4/3) << std::endl;
您可以通过测试代码确认:
std::cout << (4/3) << std::endl;
. 。
In (4 / 3)
, these are both integers so you get integer division. 在
(4 / 3)
,这些都是整数,因此你得到整数除法。 That means the result will be truncated (1.333... becomes 1). 这意味着结果将被截断(1.333 ...变为1)。 Make one of them a double so the other gets promoted to a double during division, yielding a correct result.
使其中一个成为双重,以便在分裂期间将另一个提升为双倍,从而产生正确的结果。
I prefer to use (4.0 / 3.0)
. 我更喜欢使用
(4.0 / 3.0)
。
(4/3)是一个整数表达式,因此被截断为1.尝试(4.0 / 3.0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.