2015-12-26 115 views
-1

我想比較兩個數組,如果所有的值都相同,我會做一些東西。我寫這樣的函數來檢查是否有任何不同的值。如果是這樣返回false。兩個數組有相同的值,但不返回相等

bool Deneme() 
{ 
    for (int i = 0; i < correctOnes.Length; i++) { 

     if(correctOnes[i] != cubeRotation[i].rotation.eulerAngles) 
     { 
      return false; 
     } 
    } 
    return true; 
} 

當我調用Deneme函數時,它總是返回false。但是,我檢查控制檯中的數組值,它們都是相同的。任何想法是怎麼回事?

檢查一樣,

for (int i = 0; i < correctOnes.Length; i++) { 

     Debug.Log ("Corrects: " + correctOnes[i]); 
     Debug.Log ("Cubes: " + cubeRotation[i].rotation.eulerAngles); 

    } 

控制檯照片控制檯: enter image description here

+0

一試。如果他們是平等的,你爲什麼不使用Array.Equals()? –

+0

@cFrozenDeath:出於兩個原因;因爲它是一個與數組對象中的屬性進行比較的值數組,因爲Array.Equals比較了引用而不是數組值。 – Guffa

+0

您比較的值的類型是什麼? – Guffa

回答

0

你可以有

bool Deneme() 
{ 
    for (int i = 0; i < correctOnes.Length; i++) { 

     if (!Mathf.Approximately (correctOnes[i].magnitude, cubeRotation[i].rotation.eulerAngles.magnitude))  
     { 
      return false; 
     } 
    } 
    return true; 
} 
1

這種情況最可能的原因是eulerAnglesdouble,這意味着它不應該與運營商==進行比較。兩個數字在打印時可能看起來相同,但它們會比較爲不相等。

這裏的技巧是使用Math.Abs(a-b) < 1E-8方法來比較:

if(Math.Abs(correctOnes[i]-cubeRotation[i].rotation.eulerAngles) < 1E-8) { 
    ... 
} 

以上,1E-8是代表平等比較double S上的公差小的數目。

+0

你確定'Double.Epsilon'是正確的常量?這是最小的正數可以代表一個' double'。如果我錯了,糾正我,但是這個檢查與使用'=='相同。我認爲應該使用更大的(但仍然很小)epsilon,像'1e-8' –

+0

這不適合我。double.eplision我想到的東西在4左右。 –

+0

@ÇağatayKaya我認爲epsilon對你來說太小了,試試用'1E-8'來代替 – dasblinkenlight

0

我發佈了測試腳手架的完整性,但在#35行的linq查詢應該爲您提供您的通過/失敗結果。

class Ans34467714 
{ 
    List<double> correctOnes = new List<double>() { 22.7, 22.6, 44.5, 44.5, 44.5}; 
    List<rotation> cubeRotation = new List<rotation>() { new rotation() { eulerAngles = 22.3 }, new rotation() { eulerAngles = 22.6 }, new rotation() { eulerAngles = 44.5 }, new rotation() { eulerAngles = 44.5 }, new rotation() { eulerAngles = 44.5 } }; 

    public Ans34467714() 
    { 

    } 

    internal bool Execute(string[] args) 
    { 
     bool retValue = false; 
     if (Deneme()) 
     { 
      Console.WriteLine("Pass"); 
     } 
     else 
     { 
      Console.WriteLine("Fail"); 
     } 

     return retValue; 
    } 
    internal bool Deneme() 
    { 
     return correctOnes.Where((var, index) => cubeRotation[index].eulerAngles == var).Count() == correctOnes.Count; 
    } 
} 
class rotation 
{ 
    public double eulerAngles {get; set;} 
    public rotation() 
    { 

    } 

} 
+0

謝謝你的回答,它看起來不錯,但還不能試。 –

相關問題