for循环返回

问题描述:

我在C初学者++和我有,我不知道如何解决它的问题,for循环返回

我有一个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)) ; 

有什么更简单的方法我知道我必须使用一个循环,但我不知道怎么做,在这种情况下

非常感谢

+1

耶稣的家伙,他们不是教你如何将功能分解成代表每一步的行吗?这是难以阅读或维护的... – HumbleWebDev

+0

您对

+0

对不起,我不能在这里打破它。 我用这段代码来分离一个模拟的球体,它工作的很好,而且我可以在一行中手动生成更多的球体。但由于我需要超过100个球体,因此需要大量工作才能手动完成。但手动版本的代码运行良好 – Rouzbeh

不要使用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表情把我抛回来,是一个错误吗?几乎从不会导致比较成真。目前还不清楚你在做这些比较时想做什么。所以,虽然我修改了代码,所以它等于你的想法,但它看起来很混乱,毫无意义。 > =或< =会返回1或0。或者你的意思是?

return (D <= 0.25 * diameterOfSphere*diameterOfSphere) 
      + sphere(X,Y,Z,Px,Py,Pz,diameterOfSphere, number -1);