我对 C++ 中的 C++ 编程还很陌生,但我不断收到未声明变量和没有匹配函数调用的错误。主要目标是识别 x 和 y 变量之间的空间。
#include <iostream>
#include <math.h>
using namespace std;
struct Points
{
float x, y;
};
float calcDistance(struct Point *num1, struct Point *num2)
{
float x_portion, y_portion
(x2 - x1)^2
x_portion = pow((num2->x - num1->x),2);
(y2 - y1)^2
y_portion = pow((num2->y - num1->y),2);
return sqrt(x_portion, y_portion)
}
int main()
{
Point num1;
Point num2;
float calcDistance = 0;
cout << "Enter x and y coordinate for the first point: ";
cin >> num1.x >> num1.y;
cout << "Enter the x coordinate of the second point: ";
cin >> num2.x >> num2.y;
cout << "The distance between x and y is " << calcDistance(&num1, &num2) << endl;
return 0;
}
答案 0 :(得分:0)
这是一个显示点并计算它们之间距离的代码片段:
struct Point2d
{
float x;
float y;
float distance_to(const Point2d& other) const
{
const float x_dist = x - other.x;
const float y_dist = y - other.y;
const float x_squared = x_dist * x_dist;
const float y_squared = y_dist * y_dist;
return sqrt(x_squared + y_squared);
}
};
你可以这样使用它:
Point2d a{3,4};
Point2d b{6,8};
float distance = a.distance_to(b);
您可能希望重载 operator-
而不是使用方法。
如果你不习惯结构中的方法,你可以让它独立:
float distance_between(const Point2d& a, const Point2d& b)
{
const float x_dist = a.x - b.x;
const float y_dist = a.y - b.y;
const float x_squared = x_dist * x_dist;
const float y_squared = y_dist * y_dist;
return sqrt(x_squared + y_squared);
}
我更喜欢使用 const
临时变量,因为它允许调试器显示临时值。此外,编译器会优化它们(在更高的优化设置下)。