本文介绍了这是检测负数的最佳方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 这是我的代码,我真的不能多说了。我的意思是,它工作正常,但它真的是最有效的方式吗?它看起来很脏。 D:Here is my code, I can''t really say more to it. I mean, it works fine, but is it really the most effiecient way? It looks so dirt. D:// -- Distance./// <summary>/// Returns the Pixel distance between two points./// </summary>/// <param name="Entity"></param>/// <returns></returns>public int GetDistanceFromEntity(Entity Entity){ /* Return distance. */ int OurEntityX = this.PositionX.ToString().StartsWith("-") ? -this.PositionX : this.PositionX; int OurEntityY = this.PositionY.ToString().StartsWith("-") ? -this.PositionY : this.PositionY; int OtherEntityX = Entity.PositionX.ToString().StartsWith("-") ? -Entity.PositionX : Entity.PositionX; int OtherEntityY = Entity.PositionY.ToString().StartsWith("-") ? -Entity.PositionY : Entity.PositionY; return (int)Math.Sqrt(Math.Pow(OtherEntityX - OurEntityX, 2) + Math.Pow(OtherEntityY - OurEntityY, 2));}推荐答案public int GetDistanceFromEntity(Entity Entity){ int deltaX = Entity.PositionX-PositionX; int deltaY = Entity.PositionY-PositionY; return (int)Math.Sqrt(deltaX*deltaX + deltaY*deltaY);}您可以在所有象限和两个方向上使用积分进行测试:You can test it with points in all quadrants and in both directions:var q1=new Entity(1, 2);var q2=new Entity(-3, 2);var q3=new Entity(-3, -1);var q4=new Entity(4, -1);var p0=new Entity(0, 0);Assert.AreEqual(0, q1.GetDistanceFromEntity(q1), "identiy should have distance 0");Assert.AreEqual(0, q2.GetDistanceFromEntity(q2), "identiy should have distance 0");Assert.AreEqual(0, q3.GetDistanceFromEntity(q3), "identiy should have distance 0");Assert.AreEqual(0, q4.GetDistanceFromEntity(q4), "identiy should have distance 0");Assert.AreEqual(0, p0.GetDistanceFromEntity(p0), "identiy should have distance 0");Assert.AreEqual(q2.GetDistanceFromEntity(q1), q1.GetDistanceFromEntity(q2), "distance should be invariant");Assert.AreEqual(q3.GetDistanceFromEntity(q1), q1.GetDistanceFromEntity(q3), "distance should be invariant");Assert.AreEqual(q4.GetDistanceFromEntity(q1), q1.GetDistanceFromEntity(q4), "distance should be invariant");Assert.AreEqual(p0.GetDistanceFromEntity(q1), q1.GetDistanceFromEntity(p0), "distance should be invariant");Assert.AreEqual(4, q1.GetDistanceFromEntity(q2), "distance q1-q2 mismatch");Assert.AreEqual(5, q1.GetDistanceFromEntity(q3), "distance q1-q3 mismatch");... [/ EDIT] 干杯 Andi[/EDIT]CheersAndi 这篇关于这是检测负数的最佳方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 阿里云证书,YYDS! 05-25 07:02