// 类graph的实现 #include "graph.h" #include <iostream> using namespace std; // 带参数的构造函数的实现 Graph::Graph(char ch, int n): symbol(ch), size(n) { } // 成员函数draw()的实现 // 功能:绘制size行,显示字符为symbol的指定图形样式 // size和symbol是类Graph的私有成员数据 void Graph::draw() { int i, j; for (i = 1; i <= size; i++) { for (j = 1; j <= size - i;j++) cout << " "; for (j = 1; j <= i * 2 - 1; j++) cout << symbol; for (j = 1; j <= size - 1; j++) cout << " "; cout << endl; } // 补足代码,实现「实验4.pdf」文档中展示的图形样式 }
class Fraction { public: Fraction(); Fraction(int x, int y); Fraction(int x); void show(); void add(Fraction &f1); void sub(Fraction &f1); void mul(Fraction &f1); void div(Fraction &f1); void compare(Fraction f1, Fraction f2); private: int top; int bottom; };
#include<iostream> #include"Fraction.h" using namespace std; Fraction::Fraction() { top = 0; bottom = 1; } Fraction::Fraction(int x, int b) { top = x; bottom = b; } Fraction::Fraction(int x) { top = x; bottom = 1; } void Fraction::add(Fraction &f1) { //加 Fraction f2; f2.top = top * f1.bottom + f1.top*bottom; f2.bottom = bottom * f1.bottom; f2.show(); } void Fraction::sub(Fraction &f1) { // Fraction f2; f2.top = top * f1.bottom - f1.top*bottom; f2.bottom = bottom * f1.bottom; f2.show(); } void Fraction::mul(Fraction &f1) { //乘 Fraction f2; f2.top =top*f1.top; f2.bottom =bottom*f1.bottom; f2.show(); } void Fraction::div(Fraction &f1) { //除 Fraction f2; f2.top =top*f1.bottom; f2.bottom = bottom * f1.top; f2.show(); } void Fraction::compare(Fraction f1, Fraction f2)//比较 { float a = float(f1.top) / float(f1.bottom); float b = float(f2.top) / float(f2.bottom); if (a <= b) { cout << f1.top << "/" << f1.bottom << "<="; f2.show(); cout << endl; } if (a > b) { cout << f1.top << "/" << f1.bottom << ">"; f2.show(); cout << endl; } } void Fraction::show(){ cout<<top<<"/"<<bottom<<endl; }
#include<iostream> #include"Fraction.h" using namespace std; int main() { Fraction a; Fraction b(3,4); Fraction c(5); a.show(); b.show(); c.show(); b.add(c); b.sub(c); b.mul(c); b.div(c); a.compare(b,c); return 0; }
第一题只需写一个程序比较容易,经过第二题我发现我的类方面的知识基础还不够扎实,多次参考了一些同学好的思路,以后还得多多练习