【问题标题】:C++ Distance Function Keeps Returning -1C ++距离函数不断返回-1
【发布时间】:2014-09-09 18:34:11
【问题描述】:

我创建了一个程序来计算两点之间的距离,并找到斜率。

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

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

 // 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);
    }

【问题讨论】:

  • 如果您要通过引用传递Point,最好将它们设为const...除此之外,您的代码看起来还不错。使用调试器时发生了什么?
  • 你似乎从来没有为你的点p1p2分配内存。
  • 这段代码显然不能编译。 p1p2 是未初始化的指针,您将 p1.x 视为对象,并尝试将它们的地址传递给通过引用获取对象的函数。
  • 请忽略我添加到p1和p2初始化的指针。没有它,它会编译。但是距离函数的值似乎总是1。@blastfurnace
  • 我宁愿使用指针,但我不太确定如何去做。我最近开始了解它们。 @乔什

标签: c++ pointers reference distance


【解决方案1】:

你的代码被破坏的地方:

cout << p2.x << ", " << p2.y << ") is " << distance(&p1, &p2);

您将Point * 类型的对象传递给需要Point 的函数。

为什么我们看不到编译器的错误:

因为你有using namespace std,你的代码可能实际上调用了std::distance(),它告诉你指针&amp;p1&amp;p2相距多远。

推荐阅读:

Why is "using namespace std" considered bad practice?.

【讨论】:

  • +1 我完全错过了 std::distance 正在被匹配和调用。太搞笑了。
  • 我很感激。 @blastfurnace
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
相关资源
最近更新 更多