You need to enable JavaScript to run this app. C++实现点在矩形内判断函数 指针使用报错如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

C++实现点在矩形内判断函数 指针使用报错如何解决?

错误排查

  • 缺失头文件引用:原代码使用了cin、cout输入输出方法,没有引入对应的iostream头文件,需要在代码开头补充#include <iostream>。
  • 指针成员访问错误:C++中访问指针指向的结构体成员需要使用->运算符,.仅用于直接访问结构体变量的成员,原函数内P.x、v1.x这类写法全部不符合语法要求,需要改为P->x、v1->x格式。
  • 函数调用参数错误+语法疏漏:dentroRetangulo要求传入三个指针类型参数,你直接传递了结构体变量,需要给变量加取地址符&获取对应指针;同时原if判断的括号不完整,多写了无用的空{}。

修正后完整代码

#include <iostream>
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;

    cout << "请输入矩形左下角顶点的X和Y坐标: \n";
    cout << "X = ";
    cin >> v1.x;
    cout << "Y = ";
    cin >> v1.y;
    cout << "请输入矩形右上角顶点的X和Y坐标: \n";
    cout << "X = ";
    cin >> v2.x;
    cout << "Y = ";
    cin >> v2.y;

    cout << "矩形顶点坐标为:"<<"("<<v1.x <<"," <<v1.y<<")"<<"(" <<v2.x<<","<< v2.y<<")"<<endl;
    cout<<"\n请输入待判断点的坐标"<<endl;
    cout<<"X = ";
    cin>>P.x;
    cout<<"Y = ";
    cin>>P.y;

    if (dentroRetangulo(&v1, &v2, &P)){
        cout<<"\n该点在矩形内部!"<<endl;
        cout<<"坐标为:("<<P.x<<", "<<P.y<<")"<<endl;
    }else{
        cout<<"该点在矩形外部!"<<endl;
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者Bruno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 14:24:04