我正在尝试使用嵌套的结构/结构,经过数小时的伪代码和尝试之后,我得出的最终结果不起作用或无法编译。

我想取两个向量A和B,并将它们相互比较。我设置了嵌套结构以读取矢量的起点和终点以及矢量结构本身。因此,我认为我可能会在下面做一些错误的事情,但我陷入了困境。

    #include <iostream>
    #include <cmath>
    #include <string>

    using namespace std;
struct Point    // Reads in three coordinates for point to make a three dimensional vector
{
    double x;
    double y;
    double z;
};
struct MathVector   // Struct for the start and end point of each vector.
{
    Point start;
    Point end;
};
Point ReadPoint()
{
    Point pt; // Letter distinguishes between vector A and vector B, or "letterA" and "letterB"
    double x, y, z;

    cout << "Please input the x-coordinate: " << endl;
    cin >> pt.x;
    cout << "Please input the y-coordinate: " << endl;
    cin >> pt.y;
    cout << "Please input the z-coordinate: " << endl;
    cin >> pt.z;

    return pt;
}
void DotProduct (MathVector letterA, MathVector letterB, double& a_times_b ) //formula to compute orthogonality
{
    a_times_b = (letterA.end.x - letterA.start.x)*(letterB.end.x - letterB.start.x) + (letterA.end.y - letterA.start.y)*(letterB.end.y - letterB.start.y) + (letterA.end.z - letterA.start.z)*(letterB.end.z - letterB.start.z);
}
int main()
{
    MathVector letterA;
    MathVector letterB;
    double a_times_b;

    letterA = ReadPoint();
    letterB = ReadPoint();

    DotProduct (letterA, letterB, a_times_b);

    cout << "The vector " << letterA << " compared with " << letterB << " ";
    if ( a_times_b == 0)
        cout << "is orthoganal." << endl;
    else
        cout << "is not orthoganal." << endl;

    return 0;
}

最佳答案

一个问题是您的ReadPoint的返回类型是Point,但是您正在返回MathVector的实例。同样,您将输入读入变量,这些变量最终将被忽略。

您应将ReadPoint编写为:

Point ReadPoint()
{
    Point p;
    cout << "Please input the x-coordinate: " << endl;
    cin >> p.x;
    cout << "Please input the y-coordinate: " << endl;
    cin >> p.y;
    cout << "Please input the z-coordinate: " << endl;
    cin >> p.z;
    return p;
}


或更好的版本:

Point ReadPoint()
{
    Point p;
    cout << "Please enter point-coordinate : " << endl;
    cin >> p.x >> p.y >> p.z; //example input : 1 2 3
    return p;
}


或者,更好的是,将>>运算符重载为:

std::istream & operator>>(std::istream & in, Point & p)
{
    cout << "Please enter point-coordinate : " << endl;
    return cin >> p.x >> p.y >> p.z; //example input : 1 2 3
}

//Use this as
Point pointA, pointB;
cin >> pointA >> pointB;


现在阅读一本好书。如果您已经在阅读,请确保它确实不错。这是所有级别的非常好的C ++书籍的列表:


The Definitive C++ Book Guide and List

关于c++ - C++结构未编译…未正确初始化?没有正确使用它们吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8265049/

10-12 17:16
查看更多