2017-08-04 193 views
-2

我在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

回答

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表情把我拋回來,是一個錯誤嗎?幾乎從不會導致比較成真。目前還不清楚你在做這些比較時想做什麼。所以,雖然我修改了代碼,所以它等於你的想法,但它看起來很混亂,毫無意義。 > =或< =會返回1或0。或者你的意思是?

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