문제 설명
C 프로그램에서 해당 선의 특정 점에서 특정 거리, 선 위의 점 찾기 (Find a point on a line, a certain distance from a certain point on that line in c program)
길이가 d(mod)인 두 점(a[], b[])을 지정했습니다. n이 부동 소수점 수(1.5d,0.5d,2d)인 n거리의 점을 출력할 수 있는 함수를 만들고 싶습니다. 선 사이의 기울기와 거리를 계산할 수 있지만 초기 좌표에서 nd 떨어진 선을 따라 점을 찾는 방법을 모르겠습니다.
> #include <stdio.h>
#include <math.h>
float modulus(float vec[])
{
float mod,int i,int n;
n = 2; mod = 0.0;
for (i = 0; i < n; i++)
{
mod = mod + (vec[i] * vec[i]);
}
mod = sqrt(mod);
return mod;
}
void diff(float a[], float b[], float c[])
{
int i;
for (i = 0; i < 2; i++)
c[i] = a[i] ‑ b[i];
}
float gradient(float a[], float b[])
{
int i;
float dx = a[0]‑b[0];
float dy = a[1]‑b[1];
return (dy/dx);
}
int main()
{
float a[] = {1., 1.};
float b[] = {5., 3.};
float c[2];
float len;
diff(a, b, c);
len = modulus(c);
printf("length = %.2f\n", len);
printf("\n gradient of a line : %.2f\n",gradient(a,b));
return 0;
> `Blockquote`
참조 솔루션
방법 1:
There are a couple of formulas that you can use for this type of linear interpolation (or extrapolation, when d > 1 or d < 0):
void lerp_2(float a[], float b[],
float d,
float c[])
{
c[0] = a[0] + (b[0] ‑ a[0]) * d;
c[1] = a[1] + (b[1] ‑ a[1]) * d;
}
Or
void lerp_2(float a[], float b[],
float d,
float c[])
{
c[0] = a[0] * (1.0f ‑ d) + b[0] * d;
c[1] = a[1] * (1.0f ‑ d) + b[1] * d;
}
Here, a testable implementation.
방법 2:
You don't need gradient (slope).
In your case you are given n ‑ ratio between new vector and difference vector, so calculations are simple:
for (i = 0; i < 2; i++)
result[i] = a[i] + n * c[i];
for n=0.5 new point will lie in the middle betwwen a and b
In general case of arbitrary distance you need to calculate normalized (unit length) direction vector
for (i = 0; i < 2; i++)
u[i] = c[i] / len;
and multiply it's components by needed distance
for (i = 0; i < 2; i++)
result[i] = a[i] + u[i] * needed_distance;