주어진 점으로부터 특정 거리 떨어져있는 직선상의 점을 어떻게 찾을 수 있습니까? 나는이 코드를 C로 작성하고 있지만 올바른 답을 얻지 못한다. 내가 잘못하고있는 것에 대해 나를 안내 해주는 사람이있을 수 있겠는가?C에서 직선 특정 거리를 가리킨다
나는 x1, y1, x2, y2 값을 얻고 거리는 괜찮습니다. 이것들을 사용하여 기울기 m과 y- 절편도 잘 찾을 수 있습니다. 이제 x1, y1 지점에서 10 단위 떨어져있는이 두 지점을 연결하는 직선상의 지점을 찾아야합니다. 나는 여기서 잘못 가고있는 것 같다. 여기 제가 작성한 코드가 있습니다. 여기
int x1 = node[n].currentCoordinates.xCoordinate;
int y1 = node[n].currentCoordinates.yCoordinate;
int x2 = node[n].destinationLocationCoordinates.xCoordinate;
int y2 = node[n].destinationLocationCoordinates.yCoordinate;
int distanceleft = (y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1);
distanceleft = sqrt(distanceleft);
printf("Distance left to cover is %d\n",distanceleft);
int m = (y2 - y1)/(x2 - x1); // slope.
int b = y1 - m * x1; //y-intercept
//find point on the line that is 10 units away from
//current coordinates on equation y = mx + b.
if(x2 > x1)
{
printf("x2 is greater than x1\n");
int tempx = 0;
int tempy = 0;
for(tempx = x1; tempx <= x2; tempx++)
{
tempy = y1 + (y2 - y1) * (tempx - x1)/(x2 - x1);
printf("tempx = %d, tempy = %d\n",tempx,tempy);
int distanceofthispoint = (tempy - y1) * (tempy - y1) + (tempx - x1) * (tempx - x1);
distanceofthispoint = sqrt((int)distanceofthispoint);
if(distanceofthispoint >= 10)
{
//found new points.
node[n].currentCoordinates.xCoordinate = tempx;
node[n].currentCoordinates.yCoordinate = tempy;
node[n].TimeAtCurrentCoordinate = clock;
printf("Found the point at the matching distance\n");
break;
}
}
}
else
{
printf("x2 is lesser than x1\n");
int tempx = 0;
int tempy = 0;
for(tempx = x1; tempx >= x2; tempx--)
{
tempy = y1 + (y2 - y1) * (tempx - x1)/(x2 - x1);
printf("tempx = %d, tempy = %d\n",tempx,tempy);
int distanceofthispoint = (tempy - y1) * (tempy - y1) + (tempx - x1) * (tempx - x1);
distanceofthispoint = sqrt((int)distanceofthispoint);
if(distanceofthispoint >= 10)
{
//found new points.
node[n].currentCoordinates.xCoordinate = tempx;
node[n].currentCoordinates.yCoordinate = tempy;
node[n].TimeAtCurrentCoordinate = clock;
printf("Found the point at the matching distance\n");
break;
}
}
}
printf("at time %f, (%d,%d) are the coordinates of node %d\n",clock,node[n].currentCoordinates.xCoordinate,node[n].currentCoordinates.yCoordinate,n);
동의 거라고있다. 나는 네가 정말로 여기 루프를 필요로하지 않는다고 생각한다. 이것은 알고리즘이 아니라 대수학입니다. – FlavorScape
벡터 방정식의 마지막 v가 sqrt 아래에 있거나 분수 또는 분수 바깥에 있어야합니까? 당신은 괄호를 닫는 것을 잊었습니다 :) –
오, 괜찮습니다. 이해 했어. 그것은 바깥 쪽입니다. v /를하는 대신 v에 1/..을 곱하면됩니다. –