点和圆 (类与对象)
题目描述
设计一个点类Point,包含属性:x坐标和y坐标,方法:设定坐标(setPoint),获取x坐标(getX),获取y坐标(getY)
设计一个圆类Circle,包含属性:圆心坐标x和y、半径r;方法包括:
1. 设定圆心(setCenter),设置圆心x坐标和y坐标
2. 设定半径(setRadius),设置半径长度
3. 计算面积(getArea),计算公式:面积=3.14*r*r
4. 计算周长(getLength),计算公式:周长=2*3.14*r
5. 包含(contain),判断一个圆是否包含一个点,计算圆心到这个点的距离,然后和半径做比较,大于则不包含,小于等于则包含
注意:提交代码时必须用注释划分出三个区域:类定义、类实现、主函数,如下
//-----类定义------
class XXX
{
// 写类定义代码
};
//----类实现------
void XXX::process()
{
// 写类定义代码
};
//-----主函数-----
int main()
{
//自定义一些变量
//创建一个圆对象和一个点对象
//输入圆对象和点对象的属性数值,并做初始化
//输出圆的面积和圆的周长
//输出圆是否包含点,包含则输出yes,否则输出no
return 0;
}
输入
第一行输入圆的三个整数参数:圆心的x和y坐标,半径
第二行输入点的两个整数参数:x和y坐标
输出
第一行输出圆的面积和周长,结果之间用空格隔开,输出精度到小数点后2位
第二行输出圆是否包含点,包含则输出yes,否则输出no
在C++中,输出指定精度的参考代码如下:
#include <iostream>
#include <iomanip> //必须包含这个头文件
using namespace std;
void main( )
{
double a =3.14;
cout<<fixed<<setprecision(3)<<a<<endl; //输出小数点后3位
}
涉及到私有和公有权限,所以在主函数调用的时候,不能直接接收对象的属性,要使用函数方法传参
代码示例:
1 #include <iostream> 2 #include <iomanip> 3 #include <cmath> 4 using namespace std; 5 //-----类定义----- 6 class Point 7 { 8 private: 9 int Point_x; 10 int Point_y; 11 public: 12 void setPoint(int a, int b); 13 void getX(int x); 14 void getY(int y); 15 }; 16 class Circle 17 { 18 private: 19 int Circle_x; 20 int Circle_y; 21 int r; 22 public: 23 void setCenter(int x, int y); 24 void setRadius(int r); 25 void getArea(); 26 void getLength(); 27 void contain(int x, int y); 28 }; 29 30 //-----类实现----- 31 void Point::setPoint(int a, int b) 32 { 33 getX(a); 34 getX(b); 35 } 36 void Point::getX(int x) 37 { 38 Point_x = x; 39 } 40 void Point::getY(int y) 41 { 42 Point_y = y; 43 } 44 void Circle::setCenter(int x, int y) 45 { 46 Circle_x = x; 47 Circle_y = y; 48 } 49 void Circle::setRadius(int n) 50 { 51 r = n; 52 } 53 void Circle::getArea() 54 { 55 cout << 3.14 * r * r << ' '; 56 } 57 void Circle::getLength() 58 { 59 cout << 2 * 3.14 * r << endl; 60 } 61 void Circle::contain(int p_x, int p_y) 62 { 63 //两点间距离>r,返回0;小于r,返回1 64 if (sqrt((pow((Circle_x - p_x), 2) + pow((Circle_y - p_y), 2)) < r)) 65 cout << "yes" << endl; 66 else 67 cout << "no" << endl; 68 69 } 70 71 //-----主函数----- 72 int main() 73 { 74 Point p; //定义点的对象 75 Circle c; //定义圆的对象 76 int cx, cy, r; //圆坐标 77 int x, y; //点坐标 78 cin >> cx >> cy >> r; 79 cin >> x >> y; 80 81 p.setPoint(x, y); 82 c.setCenter(cx, cy); 83 c.setRadius(r); 84 85 c.getArea(); 86 c.getLength(); 87 c.contain(x, y); 88 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)