这个类只保存长方形四个角的笛卡尔坐标值,构造函数调用一个设置函数,该设置函数接受四组坐标值,验证它们都在第一象限中,即没有一个x坐标或y坐标大于20.0,还验证提供的坐标确实能够成长方形。该类提供成员函数计算length、width、perimeter、area。其中长度是二维中的较大者。这个类还包括判定函数square,用以确定长方形是否是一个正方形。假定四个角的坐标值输入顺序为前两个坐标是左上和右上(顺序可颠倒),后两个坐标是左下和右下(顺序可颠倒)。提示:使用二维数组作为数据成员存储坐标值。
长方形判断,代码及运行结果如下:
运行结果:
代码:
#include <iostream>
#include <math.h>
using namespace std;
class Rectangle
{
public:
Rectangle(double rect[4][2])
{
m_width = 0;
m_length = 0;
setCoordinate(rect);
}
void setCoordinate(double rect[][2]) //设置坐标
{
//假定输入顺序是左上,右上,左下,右下,调整顺序,按照顺时针保存
X[0] = rect[0][0];
X[1] = rect[1][0];
X[2] = rect[3][0];
X[3] = rect[2][0];
Y[0] = rect[0][1];
Y[1] = rect[1][1];
Y[2] = rect[3][1];
Y[3] = rect[2][1];
//判断是否在第一象限
for (int i = 0; i < 4; i++)
{
if ((X[i] <= 0.0) || (X[i] > 20.0) || (Y[i] <= 0.0) || (Y[i] > 20.0))
{
cout << "有错误,请重新输入\n";
break;
}
}
//左顶点x[0],y[0],右顶点x[1],y[1] , 0 1 2节点构成直角三角形
double length1 = (X[1] - X[0]) * (X[1] - X[0]) + (Y[1]-Y[0]) * (Y[1]-Y[0]);
double width1 = (X[1] - X[2]) * (X[1] - X[2]) + (Y[1] - Y[2]) * (Y[1] - Y[2]);
double duijiaoxian = (X[2] - X[0]) * (X[2] - X[0]) + (Y[2] - Y[0]) * (Y[2] - Y[0]);
//0 2 3节点构成直角三角形
double width2 = (X[0] - X[3]) * (X[0] - X[3]) + (Y[0] - Y[3]) * (Y[0] - Y[3]);
double length2 = (X[2] - X[3]) * (X[2] - X[3]) + (Y[2] - Y[3]) * (Y[2] - Y[3]);
if (length1 == length2 && width1 == width2 && length1 + width1 == duijiaoxian)
{
isRectangle = 1;
if (length1 > width1)
{
m_length = sqrt(length1);
m_width = sqrt(width1);
}
else
{
m_length = sqrt(width1);
m_width = sqrt(length1);
}
cout << "该四边形是长方形\n";
}
else
{
isRectangle = 0;
cout << "该四边形不是长方形\n";
}
}
//获得长
double length()
{
return m_length;
}
//获得宽
double width()
{
return m_width;
}
//计算周长
double perimeter()
{
return (2 * length() + 2 * width());
}
//计算面积
double area()
{
return (length() * width());
}
//判断是否是正方形
int square()
{
if ( m_length == m_width && m_length != 0)
return 1;
else
return 0;
}
private:
double X[4], Y[4], m_width,m_length;
int isRectangle; //是否是长方形标记
};
int main()
{
double rect[4][2];
int i;
for(i=0;i<4;i++)
{
// cout<<"请输入第"<<i+1<<"个点的横纵坐标(大于0且小于20),以空格分隔:";
cin>>rect[i][0]>>rect[i][1];
}
Rectangle myRect(rect);
cout<<"长度为:"<<myRect.length()<<endl;
cout<<"宽度为:"<<myRect.width()<<endl;
cout<<"周长为:"<<myRect.perimeter()<<endl;
cout<<"面积为:"<<myRect.area()<<endl;
if(myRect.square())
cout<<"此长方形是一个正方形"<<endl;
else
cout<<"此长方形不是一个正方形"<<endl;
return 0;
}
你是要写一个Rectangle类吗?
后缀代码:
int main()
{
double rect[4][2];
int i;
for(i=0;i<4;i++)
{
// cout<<"请输入第"<<i+1<<"个点的横纵坐标(大于0且小于20),以空格分隔:";
cin>>rect[i][0]>>rect[i][1];
}
Rectangle myRect(rect);
cout<<"长度为:"<<myRect.length()<<endl;
cout<<"宽度为:"<<myRect.width()<<endl;
cout<<"周长为:"<<myRect.perimeter()<<endl;
cout<<"面积为:"<<myRect.area()<<endl;
if(myRect.square())
cout<<"此长方形是一个正方形"<<endl;
else
cout<<"此长方形不是一个正方形"<<endl;
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!