首页 > 解决方案 > C ++:比较3个Double值在明显为false时返回true +在return语句处崩溃

问题描述

所以我有这个函数,它假设只使用代表它的“角”的 3 个点来返回三角形的面积。在函数中,我必须检查所有点是否具有相同的 X 或 Y 值(因为它不是三角形)

这是函数本身:

double Triangle::getArea() const 
{
    if (_points[0].getX() == _points[1].getX() == _points[2].getX() || _points[0].getY() == _points[1].getY() == _points[2].getY())
    {
        std::cout << "Error: X values or Y values of all the points are equal";
        _exit(0);
    }
    return 0.5 * (_points[0].getX() * (_points[1].getY() - _points[2].getY()) + _points[1].getX() * (_points[0].getY() - _points[3].getY()) + _points[2].getX() * (_points[0].getY() - _points[1].getY()));
}

三角形是一个类,它继承了“Point”类的向量,该向量包含所有点(std::vector),“Point”类包含点的 X 和 Y 值。

当我尝试将此点放入函数时会出现问题:

Point point1(0, 0);
Point point2(5, 0);
Point point3(0, 6);

我还注意到,当我将第三个点更改为 (5, 0) 时,该函数不会引发我的异常,但随后它在 return 语句中崩溃并出现错误“向量下标超出范围”

这是 Triangle 的基类,称为“Polygon”,它创建点向量:

#pragma once
#include "Shape.h"
#include "Point.h"
#include <vector>

class Polygon : public Shape
{
protected:
    std::vector<Point> _points;

public:
    Polygon(const std::string& type, const std::string& name) : Shape(name, type)
    {
    }
    virtual ~Polygon()
    {
        std::vector<Point>().swap(_points);
    }

};

对不起,这个问题很长,但这个问题困扰了我很长一段时间。而且我不太确定它为什么会发生,我已经尝试并阅读了有关 Vectors 用法的更多信息,但我没有看到我的函数和 Vector 实现有什么问题。

感谢所有愿意提供帮助的人!:D

编辑:问题已经找到,我像往常一样愚蠢。检查解决方案的第一条评论

标签: c++vectordouble

解决方案


推荐阅读