20

假设左上角为(0,0),给定30度角,起点(0,300),线长600,如何计算线的终点,使线代表给定的角度。

C伪代码是

main() {
  int x,y;

  getEndPoint(30, 600, 0, 300, &x, &y);
  printf("end x=%d, end y=%d", x, y);
}

// input angle can be from 0 - 90 degrees

void getEndPoint(int angle, int len, int start_x, int start_y, int *end_x, int *end_y) 
{

    calculate the endpoint here for angle and length

    *end_x = calculated_end_x;
    *end_y = calculated_end_y;
}
4

5 回答 5

41
// edit to add conversion
    #define radian2degree(a) (a * 57.295779513082)
    #define degree2radian(a) (a * 0.017453292519)

        x = start_x + len * cos(angle);
        y = start_y + len * sin(angle);
于 2009-10-28T16:38:02.527 回答
2

你没有说相对于什么角度测量,或者你的轴的方向是什么。这些都会有所作为。

您首先需要将度数转换为弧度(乘以 PI 并除以 180)。然后你需要把你的角度的正弦和余弦乘以线的长度。现在,您的坐标有两个数字,但这取决于您的轴的方向以及测量角度的位置,这些值中的哪个是 x 坐标,哪个是 y,以及是否需要对它们中的任何一个求反。

于 2009-10-28T16:47:14.557 回答
2
// Here is a complete program with the solution in C and command-line parameters
// Compile with the math library: 
//    gcc -Wall -o point_on_circle -lm point_on_circle.c
//
// point_on_circle.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double inline degree2radian(int a) { return (a * 0.017453292519); }

void getEndPoint(double angle, int len, int start_x, 
    int start_y, int *end_x, int *end_y) {
        *end_x = start_x + len * cos(angle);
        *end_y = start_y + len * sin(angle);
} // getEndPoint

int main(int argc, char *argv[]) {
  double angle = atoi(argv[1]);
  int length   = atoi(argv[2]);
  int start_x  = atoi(argv[3]);
  int start_y  = atoi(argv[4]);
  int x, y;

  getEndPoint(degree2radian(angle), length, start_x, start_y, &x, &y);
  printf("end x=%d, end y=%d\n", x, y);

  return 0;
} // main
于 2013-10-03T02:32:02.747 回答
1

math.h具有您应该需要的所有三角函数。你可能需要给-lm你的链接器,这取决于你正在构建的系统(有时它是自动的)。

于 2009-10-28T16:37:03.543 回答
0

人们忘记了complexC++ 中的库,它为我们进行极坐标到矩形的转换。

complex<double> getEndPoint(complex<double> const &startPoint, double magnitude, double radians)
{
    return startPoint + polar<double>(magnitude, radians);
}

int main()
{
    complex<double> startingPoint(0.0, 300.0);
    auto newPoint = getEndPoint(startingPoint, 600, 0.523598776);

    cout << newPoint << endl;
}

我也会小心你选择的术语。当我看到get一个名字时,我认为它是检索存储在某处的答案。在这个例子中,我们正在计算一些东西,这可能是向您的代码用户提供的错误保证。

于 2013-11-24T19:29:42.123 回答