gpt4 book ai didi

C++ 距离函数不断返回 -1

转载 作者:太空宇宙 更新时间:2023-11-04 15:03:06 24 4
gpt4 key购买 nike

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

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

最佳答案

你的代码在哪里被破坏:

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

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

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

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

推荐阅读:

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

关于C++ 距离函数不断返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25751478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com