2017-10-05 107 views
1

我有這個功能,我想傳遞兩個Vector3參數和一個int,所以我可以返回一個浮點值。我怎樣才能返回一個浮點值,即使我使用Vector3和int作爲參數? 這是我的代碼:如何從具有不同類型參數的函數返回浮點數?

//find other types of distances along with the basic one 
public object DistanceToNextPoint (Vector3 from, Vector3 to, int typeOfDistance) 
{ 
    float distance; 
    //this is used to find a normal distance 
    if(typeOfDistance == 0) 
    { 
     distance = Vector3.Distance(from, to); 
     return distance; 
    } 
    //This is mostly used when the cat is climbing the fence 
    if(typeOfDistance == 1) 
    { 
     distance = Vector3.Distance(from, new Vector3(from.x, to.y, to.z)); 
    } 
} 

當我用「迴歸」 keyworkd取代「對象」關鍵字它給了我這個錯誤; enter image description here

+5

你可能希望在聲明和返回距離中把'object'改成'float'。 – 2017-10-05 13:50:29

+0

是的,所有的答案和評論都指向了答案;) –

回答

5

您的代碼存在兩個問題。

  1. 如果你想要返回一個對象類型,那麼你需要在使用它之前將結果強制轉換爲浮點型。
  2. 並非所有的代碼路徑都返回一個值。

你可以試試這個:

/// <summary> 
/// find other types of distances along with the basic one 
/// </summary> 
public float DistanceToNextPoint (Vector3 from, Vector3 to, int typeOfDistance) 
{ 
    float distance; 

    switch(typeOfDistance) 
    { 
     case 0: 
      //this is used to find a normal distance 
      distance = Vector3.Distance(from, to); 
     break; 
     case 1: 
      //This is mostly used when the cat is climbing the fence 
      distance = Vector3.Distance(from, new Vector3(from.x, to.y, to.z)); 
     break; 
    } 

    return distance; 
} 

的變化包括:

  • 返回float類型,而不是對象
  • 確保所有代碼路徑返回浮點型
  • 重新組織使用開關
+0

謝謝你的回答,簡而言之,關鍵點,以及使代碼更有效的方法。 – Noobie

2

剛剛從object改變返回類型float這樣的:

public object DistanceToNextPoint(...) 

要:

public float DistanceToNextPoint(...){ 
    // ... 
    return distance: 
} 

public float DistanceToNextPoint(...) 

然後在方法的最後一行返回您的變量distance

+0

謝謝,很好的回答! – Noobie

2

您應該將return類型object更改爲float

//finde other tipe of distances along with the basic one 
    public float DistanceToNextPoint (Vector3 from, Vector3 to, int tipeOfDistance) 
    { 
     float distance; 
     //this is used to find a normal distance 
     if(tipeOfDistance == 0) 
     { 
      distance = Vector3.Distance(from, to); 
      return distance; 
     } 
     //This is mostly used when the cat is climbing the fence 
     if(tipeOfDistance == 1) 
     { 
      distance = Vector3.Distance(from, new Vector3(from.x, to.y, to.z)) 
      return distance; 
     } 
    } 
相關問題