构造一个矩形类Rectangle,数据成员为矩形的左下角与右上角的坐标,并利用成员函数实现对矩形周长与面积的计算
#include <iostream>
class Rectangle
{
public:
Rectangle(double x1, double y1, double x2, double y2) : _x1(x1), _y1(y1), _x2(x2), _y2(y2) {}
double perimeter() const
{
return std::abs(_x1 - _x2) * 2.0 + std::abs(_y1 - _y2) * 2.0;
}
double area() const
{
return std::abs(_x1 - _x2) * std::abs(_y1 - _y2);
}
private:
double _x1;
double _y1;
double _x2;
double _y2;
};
int main()
{
double x1, y1, x2, y2;
std::cout << "输入左下角坐标: ";
std::cin >> x1 >> y1;
std::cout << "输入右上角坐标: ";
std::cin >> x2 >> y2;
Rectangle r(x1, y1, x2, y2);
std::cout << "周长: " << r.perimeter() << std::endl;
std::cout << "面积: " << r.area() << std::endl;
return 0;
}
#include <iostream>
#include <math.h>
using namespace std;
class Rectangle
{
public:
double x, y; //左下
double _x, _y; //右上
Rectangle(double x, double y, double _x, double _y)
{
this->x = x;
this->y = y;
this->_x = _x;
this->_y = _y;
}
void p()
{
cout << "周长:" << 2 * fabs(x - _x) + 2 * fabs(y - _y) << endl;
}
void area()
{
cout << "面积:" << fabs(x - _x) * fabs(y - _y) << endl;
}
};
int main(void)
{
double x, y;
double _x, _y;
cout << "输入左下坐标(x,y):";
cin >> x >> y;
cout << "输入右上坐标(_x,_y):";
cin >> _x >> _y;
Rectangle rec(x, y, _x, _y);
rec.p();
rec.area();
return 0;
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
class printS {
public:
float x; float y;
};
class Rectangle {
public:
printS pointA;
printS pointB;
float zc() {
float length = 0;
float width = 0;
if (pointA.x>pointB.x)
{
width = pointA.x - pointB.x;
}
else
{
width = pointB.x - pointA.x;
}
if (pointA.y > pointB.y)
{
length = pointA.y - pointB.y;
}
else
{
length = pointB.y - pointA.y;
}
return 2 * (width + length);
}
float mj() {
float length = 0;
float width = 0;
if (pointA.x > pointB.x)
{
width = pointA.x - pointB.x;
}
else
{
width = pointB.x - pointA.x;
}
if (pointA.y > pointB.y)
{
length = pointA.y - pointB.y;
}
else
{
length = pointB.y - pointA.y;
}
return length * width;
}
};
int main()
{
float x1, y1,x2,y2;
Rectangle* rec = (Rectangle*)malloc(sizeof(Rectangle));
printf("输入左下角坐标(用空格隔开):");
scanf("%f%f",&x1,&y1);
printf("输入右上角坐标(用空格隔开):");
scanf("%f%f", &x2, &y2);
rec->pointA.x = x1;
rec->pointA.y = y1;
rec->pointB.x = x2;
rec->pointB.y = y2;
printf("矩形面积是:%f",rec->mj());
printf("矩形周长是:%f", rec->zc());
return 0;
}