我有一个代码:同样的结构有不同的hashCode
public class Point
{
public int x;
public int y;
public Point() { x = 0; y = 0; }
public Point(int a, int b) { x = a; y = b; }
}
public struct Coefficients{
public double a;
public double b;
public double c;
public Coefficients(double a, double b, double c)
{
this.a = a;
this.b = b;
this.c = c;
}
public static Coefficients GetFromPoints(Point point1, Point point2)
{
int x1 = point1.x;
int x2 = point2.x;
int y1 = point1.y;
int y2 = point2.y;
double a = y1- y2;
double b = x2 - x1;
double c = x1 * y2 - y1 * x2 ;
double max = Math.Max(Math.Max(a, b), c);
double min= Math.Min(Math.Min(a, b), c);
double divider = Math.Abs(max)> Math.Abs(min)?max:min;
divider = Math.Abs(divider) > 1? divider : 1;
return new Coefficients(a/divider, b/divider, c/divider);
}
}
public class Solution
{
public int MaxPoints(Point[] points)
{
var coef_list = new List<Coefficients>();
for (var x = 0; x < points.Length - 1; x++)
{
for (var y = x + 1; y < points.Length; y++)
{
var coef = Coefficients.GetFromPoints(points[x], points[y]);
coef_list.Add(coef);
}
}
foreach (var item in coef_list) {
Debug.WriteLine(item.a);
Debug.WriteLine(item.b);
Debug.WriteLine(item.c);
Debug.WriteLine(item.GetHashCode());
Debug.WriteLine("---------------");
}
return 0;
}
}
正如你可以看到我使用struct和我说怪异的行为。 如果我有这样的输入数据:
prg.MaxPoints(new Point[] { new Point(4, -1), new Point(4, 0), new Point(4, 5) });
调试输出是:
-0,25
0
1
-450335288
---------------
-0,25
0
1
-450335288
---------------
-0,25
0
1
-450335288
---------------
但如果我改变ARGS。为了:
prg.MaxPoints(new Point[] { new Point(4, 0),new Point(4, -1) , new Point(4, 5) });
调试的是:
-0,25
0
1
1697148360
---------------
-0,25
0
1
-450335288
---------------
-0,25
0
1
-450335288
---------------
而且有一件事情是很重要的是,在第一种情况下,我们有所有的“分隔”(GetFromPoints法)是正(4 ,24,20)在第二种情况下,其中一个为负数,另外两个为正数(-4,20,24)。 有人可以解释这一点吗?
UPD。 当我改变
return new Coefficients(a/divider, b/divider, c/divider);
到
return new Coefficients(a/divider, 0, c/divider);//anyway in all of these cases 2-nd argument is 0
这意味着0由负分割不为0?
是的,但我认为具有相同字段的结构应该是相等的,但它们不是。 '调试。写入(coef_list [0] .a.Equals(coef_list [1] .a)); Debug.WriteLine(coef_list [0] .b.Equals(coef_list [1] .b)); Debug.WriteLine(coef_list [0] .c.Equals(coef_list [1] .c)); 的Debug.WriteLine(coef_list [0] .Equals(coef_list [1]));' 显示 '真 真正 真正 FALSE' –
他们是不相等的,你的数学给你一个舍入误差,所以' - 0,25'可能不是。当输出a,b和c值时,使用'.ToString(“G17”)' –
偷看字节,看起来可能是某种下溢,因为它们不完全相同字节,但给出理论上相等的值。在第一种情况下,第一个组件的“b”正好为零:“0 0000000000000000”,而在第二种情况下,它略有不同:“0 0000000000000080”。 –