我是C ++的初学者,我有一个问题,我不知道如何解决它,
我有一个int函数,它应该返回很少的参数:
int sphere(const float & X,const float & Y,const float & Z,
const int & Px, const int & Py, const int & Pz,
const int & diameterOfSphere, const int & number)
{
return pow(Px-X,2) + pow(Py+(diameterOfSphere * (number - 1))-Y,2)
+ pow(Pz-Z,2) <= pow(diameterOfSphere/2,2);
}
在这个函数中,整数“数字”可能应该从2开始到例如100.我需要做一些事情,如果我选择100为“数字”,则返回语句应重复99次并用加(+)。
例如我可以手动完成,但需要编写大量不合逻辑的代码
例如,我手动完成了三次 return (pow(Px-X,2)+pow((Py+(diameterOfSphere * 2))-Y,2)+pow(Pz-Z,2)
<= pow(diameterOfSphere/2,2))
+ (pow(Px-X,2)+pow((Py+(diameterOfSphere * 3))-Y,2)+pow(Pz-Z,2)
<= pow(diameterOfSphere/2,2))
+ (pow(Px-X,2)+pow((Py+(diameterOfSphere * 4))-Y,2)+pow(Pz-Z,2)
<= pow(diameterOfSphere/2,2))
+ (pow(Px-X,2)+pow((Py+(diameterOfSphere * 5))-Y,2)+pow(Pz-Z,2)
<= pow(diameterOfSphere/2,2)) ;
有没有更简单的方法?我知道我必须使用循环,但我不知道在这种情况下如何做到
非常感谢
答案 0 :(得分:1)
不要使用pow()
来执行球体方格,而pow()是一个非常慢的指数函数。打破您的公式并格式化您的行以使代码可读。 你的点的坐标是整数,是故意的吗?这个变体不仅更具可读性,而且更有可能被编译器优化:
int sphere(const float & X,const float & Y, const float & Z,
const int & Px, const int & Py, const int & Pz,
const int & diameterOfSphere, const int & number)
{
const float dx = Px - X;
const float dy = Py + diameterOfSphere * (number - 1) - Y;
const float dz = Pz - Z;
const float D = dx*dx + dy*dy + dz*dz;
return D <= 0.25 * diameterOfSphere*diameterOfSphere;
}
现在如果我理解正确,你需要一个递归或一个模拟递归的循环。你实际上可以自己调用函数,你知道吗?
int sphere(const float & X,const float & Y, const float & Z,
const int & Px, const int & Py, const int & Pz,
const int & diameterOfSphere, const int & number)
{
const float dx = Px - X;
const float dy = Py + diameterOfSphere * (number - 1) - Y;
const float dz = Pz - Z;
const float D = dx*dx + dy*dy + dz*dz;
if(!(number>0))
return 0;
return D <= 0.25 * diameterOfSphere*diameterOfSphere
+ sphere(X,Y,Z,Px,Py,Pz,diameterOfSphere, number -1);
}
递归的反面a)每个函数调用用存储的变量和参数填充堆栈b)有一个额外的调用立即返回。
Py + diameterOfSphere * (number - 1) - Y
表达式抛弃了我,这是一个错误吗?几乎从来都不会导致比较成真。并且还不清楚你正在尝试用这些比较做些什么。因此,虽然我修改了代码以使其与您的想法相同,但它看起来很混乱\毫无意义。 &gt; =或&lt; =将返回1或0作为结果。或者你是说这个?
return ( D <= 0.25 * diameterOfSphere*diameterOfSphere )
+ sphere(X,Y,Z,Px,Py,Pz,diameterOfSphere, number -1);