两点之间的距离和角度

时间:2016-04-01 13:48:09

标签: c#

角度输出错误只有45而不是-135.000被告知?

我被告知使用以下输入1X = 2,1Y = 2,2X = 1,2Y = 1, 计算距离 - 输出数字1.414(到3 位)。此外,我还被告知使用计算角度 Atan2并将弧度转换为度数 - 输出45.但是......我 有人告诉我这个角度的输出应该是-135.000度?

我知道我某处遗漏了什么?

全部排序!非常感谢The Oddler:)

- (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector
{
    BOOL result = NO;

    if (commandSelector == @selector(insertTab:)) {

        // tab action:
        // always insert a tab character and don’t cause the receiver to end editing
        if ([self.nextKeyView isKindOfClass:[NSTextField class]]) {

            [(NSTextField *)self.nextKeyView selectText:self];
            result = YES;

        } else {

            //[textView insertTabIgnoringFieldEditor:self];
            result = NO;

        }

    }

    return result;
}

2 个答案:

答案 0 :(得分:1)

在c#中,变量不能以数字开头,因此1X不是有效的变量名。将其更改为X1,它应该没问题。另外,请确保不要使用平方三角形作为角度。

float X1=2, Y1=2, X2=1, Y2=1; //Don't start variable names with number

//calculate delta x and delta y between the two points
var deltaX = Math.Pow((X2 - X1), 2); 
var deltaY = Math.Pow((Y2 - Y1), 2);

//pythagras theorem for distance
var distance = Math.Sqrt(deltaY + deltaX);

//atan2 for angle
var radians = Math.Atan2((Y2 - Y1), (X2 - X1)); // Don't use squared delta

//radians into degrees
var angle = radians * (180 / Math.PI);

Console.WriteLine("Dist = " + distance);
Console.WriteLine("Angle = " + angle);

让它显示出来有点小提琴:https://dotnetfiddle.net/fzyVFW

答案 1 :(得分:1)

问题是deltaX和deltaY在你的代码中是平方的。所以

radians = Math.Atan2(deltaY, deltaX);

返回错误的数字。

我没有测试过,但是

//calculate delta x and delta y between the two points

deltaX = X2 - X1;
deltaY = Y2 - Y1;

//pythagoras theorem for distance
distance = Math.Sqrt(deltaX*deltaX + deltaY*deltaY);

//atan2 for angle
radians = Math.Atan2(deltaY, deltaX);

//radians into degrees
angle = radians * (180 / Math.PI);

应该有用。