提问者:小点点

C#:使用大于30亿的数字进行计算将返回NaN


总的来说,我对C#和编程还是个新手。 我在计算一条线和一个椭圆的交点。 当椭圆半径大于1f时,代码按预期工作。

当半径(大约)小于1F时,“t”返回NaN。

我已经用手计算了这些数字,我注意到当半径低于1f时,B*B=30亿+。

我曾尝试将“t”转换为双倍,并尝试使用System.Math而不是Mathf。 当radius<; 1f。

任何反馈都非常感谢!

public static Vector2 GetEllipseOuterIntersection(Vector2 ellipseCentre, float radius, Vector2 lightDot, Vector2 objectDot) {

    lightDot.x -= ellipseCentre.x;
    lightDot.y -= ellipseCentre.y;
    objectDot.x -= ellipseCentre.x;
    objectDot.y -= ellipseCentre.y;

    // Get the semiminor axis.
    float vertRadius = radius/2;

    // Calculate the quadratic parameters.
    float A = (objectDot.x - lightDot.x) * (objectDot.x - lightDot.x) / radius / radius + (objectDot.y - lightDot.y) * (objectDot.y - lightDot.y) / vertRadius / vertRadius;
    float B = 2 * lightDot.x * (objectDot.x - lightDot.x) / radius / radius + 2 * lightDot.y * (objectDot.y - lightDot.y) / vertRadius / vertRadius;
    float C = lightDot.x * lightDot.x / radius / radius + lightDot.y * lightDot.y / vertRadius / vertRadius - 1;

    double t = (-B + System.Math.Sqrt(B*B - (4*A*C))) / 2 / A;

    print(t);

    float x = (float) (lightDot.x + (objectDot.x - lightDot.x) * t + ellipseCentre.x);
    float y = (float) (lightDot.y + (objectDot.y - lightDot.y) * t + ellipseCentre.y);

    Vector2 outerIntersection = new Vector2(x, y);

    return outerIntersection;
}

共1个答案

匿名用户

请尝试使用long。

长值比整数高得多。

// first number
long myLongNumber = 2345608830;

// second number
long secondLong = myLongNumber * 3;

秒长结果:7036826490

编辑:我没看到你需要小数。 如果四舍五入到整数是一个问题,那么您可能需要一些其他解决方案。