gpt4 book ai didi

C++ 结构未编译...未正确初始化?没有正确使用它们?

转载 作者:行者123 更新时间:2023-11-28 03:43:57 25 4
gpt4 key购买 nike

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

我想取两个 vector A 和 B,并将它们相互比较。我设置了嵌套结构来读取 vector 的起点和终点,以及 vector 结构本身。所以我想我可能在下面做错了,但我被卡住了。

    #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++ 书。如果您已经读过一本,那么确保它真的不错。以下是所有级别的真正优秀的 C++ 书籍列表:

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

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