C++ C++;距离函数保持返回-1

C++ C++;距离函数保持返回-1,c++,pointers,reference,distance,C++,Pointers,Reference,Distance,我创建了一个程序,可以计算两点之间的距离,并找到坡度 1) 我如何将程序更改为严格的指针 2) 无论输入是什么,距离函数都返回“-1”。我百分之百肯定我的算术是正确的,但似乎出了点问题 // This program computes the distance between two points // and the slope of the line passing through these two points. #include<iostream> #

我创建了一个程序,可以计算两点之间的距离,并找到坡度

1) 我如何将程序更改为严格的指针

2) 无论输入是什么,距离函数都返回“-1”。我百分之百肯定我的算术是正确的,但似乎出了点问题

 // This program computes the distance between two points
 // and the slope of the line passing through these two points.

    #include<iostream>
    #include<iomanip>
    #include<cmath>
    using namespace std;

    struct Point
    {
        double x;
        double y;
    };

    double distance(Point &p1, Point &p2);
    double slope(Point &p1, Point &p2);

    int main()
    {
        Point p1, p2;
        char flag = 'y';
        cout << fixed << setprecision(2);
        while(flag == 'y' || flag == 'Y')
        {
            cout << "First x value: "; cin >> p1.x;
            cout << "First y value: "; cin >> p1.y;
            cout << "Second x value: "; cin >> p2.x;
            cout << "Second y value: "; cin >> p2.y; cout << endl;

            cout << "The distance between points (" << p1.x << ", " << p1.y << ") and (";
            cout << p2.x << ", " << p2.y << ") is " << distance(&p1, &p2);

            if ((p2.x - p1.x) == 0)
            { cout << " but there is no slope." << endl; cout << "(Line is vertical)" << endl; }
            else
            { cout << " and the slope is " << slope(p1, p2) << "." << endl; }

            cout << endl;
            cout << "Do you want to continue with another set of points?: "; cin>> flag;
            cout << endl;
        }
        return 0;
    }

    double distance(Point &p1, Point &p2)
    {
        return sqrt((pow((p2.x - p1.x), 2) + pow((p2.y - p1.y), 2)));
    }

    double slope(Point &p1, Point &p2)
    {
        return (p2.y - p1.y) / (p2.x - p1.x);
    }
//此程序计算两点之间的距离
//通过这两点的直线的斜率。
#包括
#包括
#包括
使用名称空间std;
结构点
{
双x;
双y;
};
双距离(点和p1、点和p2);
双坡度(点和p1、点和p2);
int main()
{
点p1,p2;
字符标志='y';
cout p1.y;
cout>p2.x;
cout>p2.y;cout代码被破坏的位置:

cout如果你要通过引用来传递
点,你最好让它们成为
const
…除此之外,你的代码看起来很好。当你使用调试器时发生了什么?你似乎从来没有为点
p1
p2
分配内存。这段代码显然不可编译。
p1
p2
是未初始化的指针,您可以将它们当作对象,尝试将它们的地址传递给引用对象的函数。请忽略我添加到p1和p2初始化中的指针。如果没有这些指针,它将编译。但是距离函数的值似乎总是1。@blastfurnaceI'd rather使用指针,但我不太确定如何去做。我最近开始学习它们。@Josh+1我完全错过了正在匹配和调用的
std::distance
。这太好笑了。我很感激。@blastfunner
cout << p2.x << ", " << p2.y << ") is " << distance(&p1, &p2);