1. 分数类
Fract.cpp
#include"Fract.h" #include<iostream> using namespace std; int Fract::ged(int m, int n) { int v,a=m,b=n; v = a % b; while (v != 0) { a = b; b = v; v = a % b; } return b; } Fract Fract::add(Fract f2) { int v; v = ged(den, f2.den); int com; com = den * f2.den / v; Fract f3(0,1); num = num * (com / den); f2.num = f2.num * (com / f2.den); f3.num = num + f2.num; f3.den = com; v = ged(f3.num, f3.den); f3.num = f3.num / v; f3.den = f3.den / v; return f3; }
main.cpp
#include"Fract.h" #include<iostream> using namespace std; int main() { int a, b, c, d; cin >> a >> b >> c >> d; Fract f1(a, b); Fract f2(c, d); Fract f3(0,1); f3 = f1.add(f2); f3.show(); return 0; }
2.圆类
【问题描述】编写圆的类
【样例输入】【样例输出】
请输入圆的半径:23
圆的面积为:1661.06
圆的周长为:144.44
const float PI = 3.14; #pragma once class Circle { public: Circle(double _r) { r = _r; } double getArea() { return 3.14 * r * r; } double getGirth() { return 2 * 3.14 * r; } private: double r; }; #include<iostream> using namespace std; int main() { float r; cout << "请输入圆的半径:"; cin >> r; //从键盘接受半径的值 Circle c1(r); //将值赋值给半径并调用定义好的函数 cout<<"圆的面积为:"<<c1.getArea()<<endl; Circle c2(r); cout<<"圆的周长为:"<<c2.getGirth()<<endl; }
3.编写矩形类
【问题描述】编写程序求长方形的周长和面积
【输入形式】
【输出形式】
【样例输入】【样例输出】
Input the Length and Width: 12 23
The Area is:276
The Premeter:70
#include <iostream> class Rectangle { public: Rectangle(void); Rectangle(float length,float width); ~Rectangle(void); float getArea(); float getGirth(); private: float mLength; float mWidth; }; Rectangle::Rectangle() { mLength = 0; mWidth = 0; } Rectangle::Rectangle(float length, float width) { mLength = length; mWidth = width; } float Rectangle::getArea() { return mLength * mWidth; } float Rectangle::getGirth() { return 2 * (mLength + mWidth); } Rectangle::~Rectangle(void) { } #include<iostream> using namespace std; int main() { float m, n; cout << "Input the Length and Width: "; cin >> m >> n; Rectangle r1(m,n); cout<<"The Area is: "<<r1.getArea()<<endl; Rectangle r2(m,n); cout<<"The Perimeter: "<<r2.getGirth()<<endl; }