2015-12-26 112 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

谢谢你的回答,它看起来不错,但还不能试。 –

相关问题