感谢B站黑马程序员!有兴趣的可以去B站详细学习!
黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难_哔哩哔哩_bilibili
二、点与圆的关系:
设计一个圆形类(Circle),和一个点类(Point),计算点和圆的关系。
这此项目的学习我终于知道头文件与源文件之间的关系与“::”是怎么用的了,::就是当你在源文件中编写函数时,你需要告诉系统你编写的是哪一个类中的函数,作用于哪一个类。
1、设计点类:
此项目利用头文件声明,源文件实现函数功能(前三行代码作用给出):
#pragma once //防止头文件重复包含
#include <iostream> //标准的输入输出
using namespace std; //标准的命名空间
class point
{
public:
void setx(int x);
int getx();
void sety(int y);
int gety();
private:
int m_x;
int m_y;
};
功能在源文件中实现:
#include "point.h"
void point::setx(int x)
{
m_x = x;
}
int point::getx()
{
return m_x;
}
void point::sety(int y)
{
m_y = y;
}
int point::gety()
{
return m_y;
}
2、同样,设计圆形类:
#pragma once
#include <iostream>
#include "point.h"
using namespace std;
class circle
{
public:
void setr(int r);
int getr();
void setcenter(point center);
point getcenter();
private:
int m_r;
point m_circlecenter;
};
与圆形类功能实现:
#include "circle.h"
void circle::setr(int r)
{
m_r = r;
}
int circle::getr()
{
return m_r;
}
void circle::setcenter(point center)
{
m_circlecenter = center;
}
point circle::getcenter()
{
return m_circlecenter;
}
3、在主函数中的源文件中加入判断函数,判断依据为点与圆心x,y坐标相减的平方与半径r的平方相比较,通过if语句给出输出:
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
#include "circle.h"
#include "point.h"
void panduan(circle &c,point &p)
{
int res = pow(c.getcenter().getx() - p.getx(), 2) + pow((c.getcenter().gety() - p.gety()), 2);
/*int tem = ((c.getcenter().getx() - p.getx()) * (c.getcenter().getx() - p.getx()))
+ ((c.getcenter().gety() - p.gety()) * (c.getcenter().gety() - p.gety()));*/
int r = pow(c.getr(), 2);
/*int t = c.getr() * c.getr();*/
cout << res << endl;
cout << r << endl;
/*cout << tem << endl;
cout << t << endl;*/
if (res > r)
{
cout << "点在圆外!!!" << endl;
}
else if (res == r)
{
cout << "点在圆上!!!" << endl;
}
else
{
cout << "点在圆内!!!" << endl;
}
}
int main()
{
circle c;
point center;
c.setr(10);
center.setx(10);
center.sety(0);
c.setcenter(center);
point p;
p.setx(10);
p.sety(11);
panduan(c, p);
system("pause");
}
友情提示:
建议自己动手打代码!
该篇博客介绍了如何使用C++设计一个圆形类(Circle)和点类(Point),实现计算点与圆的位置关系。讲解了头文件与源文件的使用,以及如何通过点的坐标和圆的半径判断点在圆内、圆上或圆外。此外,还提供了完整的代码示例,鼓励读者动手实践。
6万+

被折叠的 条评论
为什么被折叠?



