[英]Could anyone help me with what is wrong in the below piece of c++ code? The program doesn't give any output
[英]C++ BOOL FUNCTION WITH * , could you help me? What is wrong with my code?
问题:考虑一个结构来表示二维空间中的一个点,并实现一个 function 来指示给定点 p 是位于矩形内部还是外部。 矩形由其左下 v1 和右上 v2 顶点定义。 如果该点位于矩形内,则 function 必须返回 true,否则返回 false。 这个 function 必须服从以下原型: bool dentroRetangulo(Ponto* v1, Ponto* v2, Ponto* P);
我的代码:
using namespace std;
struct Ponto{
int x;
int y;
};
bool dentroRetangulo(Ponto* v1, Ponto* v2, Ponto* P){
if ((P.x>=v1.x && P.x<=v2.x)&&(P.y>=v1.y && P.y<=v2.y))
return true;
return false;
}
int main(){
Ponto v1,v2,P;
//int x, y;
cout << "Insert the X and Y from the vertex of the lower left rectangle: \n";
cout << "X = ";
cin >> v1.x;
cout << "Y = ";
cin >> v1.y;
cout << "Insert the X and Y from the vertex of the upper right rectangle: \n";
cout << "X = ";
cin >> v2.x;
cout << "Y = ";
cin >> v2.y;
cout << "The coordinates of the rectangle vertices are: "<<"("<<v1.x <<"," <<v1.y<<")"<<"(" <<v2.x<<","<< v2.y<<")"<<endl;
cout<<"\nEnter the position of the point"<<endl;
cout<<"X = ";
cin>>P.x;
cout<<"Y = ";
cin>>P.y;
if (dentroRetangulo(v1, v2, P){} // Here I am not able to call the function correctly due to the pointer
cout<<"\nThis Point is inside the Rectangle !"<<endl;
cout<<"("<<P.x<<")"<<" "<<"("<<P.y<<")"<<endl;
}else{
cout<<"This point is outside the rectangle !"<<endl;
}
return 0;
}
对于签名bool dentroRetangulo(Ponto* v1, Ponto* v2, Ponto* P)
,您有 3 个指针 arguments。 所以你需要使用->
来访问数据成员。
要传递指针 arguments,您需要使用&
。
现代编译器的编译错误消息非常清楚,只需按照它们并修复您的代码即可。
#include <ostream>
using namespace std;
struct Ponto {
int x;
int y;
};
bool dentroRetangulo(Ponto* v1, Ponto* v2, Ponto* P) {
if ((P->x >= v1->x && P->x <= v2->x) && (P->y >= v1->y && P->y <= v2->y))
return true;
return false;
}
int main() {
Ponto v1, v2, P;
// int x, y;
cout << "Insert the X and Y from the vertex of the lower left rectangle: \n";
cout << "X = ";
cin >> v1.x;
cout << "Y = ";
cin >> v1.y;
cout << "Insert the X and Y from the vertex of the upper right rectangle: \n";
cout << "X = ";
cin >> v2.x;
cout << "Y = ";
cin >> v2.y;
cout << "The coordinates of the rectangle vertices are: "
<< "(" << v1.x << "," << v1.y << ")"
<< "(" << v2.x << "," << v2.y << ")" << endl;
cout << "\nEnter the position of the point" << endl;
cout << "X = ";
cin >> P.x;
cout << "Y = ";
cin >> P.y;
if (dentroRetangulo(&v1, &v2, &P)) { // Here I am not able to call the
// function correctly due to the pointer
cout << "\nThis Point is inside the Rectangle !" << endl;
cout << "(" << P.x << ")"
<< " "
<< "(" << P.y << ")" << endl;
} else {
cout << "This point is outside the rectangle !" << endl;
}
return 0;
}
在线演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.