编写C++计算程序 - 方程y=kx+t上的两点的距离

计算 y = kx+t 上 两点(x0,y0), (x1,y1)之间的距离

计算方法是y0 = k*x0+t, y1 = k*x1+t;

然后两点的距离公式 为 s = sqrt( (y1-y0) * (y1-y0)  +  (x1-x0)*(x1-x0) )

得到了,这个初中代数,我们用C / C++写程序就是下面这样的

#include <iostream>
#include <math.h>
using namespace std;

// y = kx+t
float f(float k, float t, float x)
{
    return k*x+t;
}

float getLength(float k, float t, float x0, float x1)
{
    float y0 = f(k,t,x0);
    float y1 = f(k,t,x1);
    float dx = x1 - x0;
    float dy = y1 - y0;
    float s = sqrt(dx*dx+dy*dy);
    
    return s;
}

int main()
{
    float k = 1.f;
    float t = 2.f;
    float s = getLength(k, t, 0.f, 1.f);
    cout << "length is " << s << endl; 
    return 0;
}

可以拷贝到 https://c.runoob.com/compile/12 运行,结果为 length is 1.41421

posted @ 2021-01-10 20:19  abcstar  阅读(183)  评论(0编辑  收藏  举报