实验4
#include <iostream> #include"graph.h" /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main() { Graph graph1('*',5); Graph graph2('$',7);// 定义类的对象graph以及graph2,并利用构造函数对其进行初始化 graph1.draw();//引用函数draw完成绘图 graph2.draw(); return 0 ; }
#include"graph.h" #include<iostream> using namespace std; Graph::Graph(char ch,int n):symbol(ch),size(n){} void Graph::draw()//draw函数的实现 { int i,j,n; for(i=0;i<size;i++) { n=2*size-1;//n为每行输出的字符数 for(j=0;j<=n;j++) { if(j<size-i||j>size+i) cout<<" "; else cout<<symbol; }cout<<endl; } }
graph.h
#ifndef GRAPH_H #define GRAPH_H class Graph { public: Graph(char ch,int n); //构建构造函数 void draw(); private: char symbol; int size; }; #endi
fraction.h
class Fraction{ public: Fraction(int t0,int b0); Fraction(); Fraction(int t0); void add(Fraction &p1,Fraction &p2); void sub(Fraction &p1,Fraction &p2); void mul(Fraction &p1,Fraction &p2); void div(Fraction &p1,Fraction &p2); void compare(Fraction &p1,Fraction &p2); void show(); private: int top; int bottom; };
#include <iostream> #include"fraction.h" /* run this program using the console pauser or add your own getch, system("pause") or input loop */ #include <iostream> #include"fraction.h" using namespace std; int main() { Fraction a; Fraction b(3,4);
#include<iostream> #include"Fraction.h" using namespace std; //函数的实现 Fraction::Fraction(){ top=0; bottom=1; } Fraction::Fraction(int x,int y){ top=x; bottom=y; } Fraction::Fraction(int x){ top=x; bottom=1; } void Fraction::show() { cout<<top<<'/'<<bottom<<endl; } void Fraction::add(Fraction &a,Fraction &b) { a.top=top*b.bottom+b.top*bottom; a.bottom=bottom*b.bottom; a.show(); } void Fraction::sub(Fraction &a,Fraction &b) { a.top=top*b.bottom-b.top*bottom; a.bottom=bottom*b.bottom; a.show(); } void Fraction::mul(Fraction &a,Fraction &b) { a.top=top*b.top; a.bottom=bottom*b.bottom; a.show(); } void Fraction::div(Fraction &a,Fraction &b) { a.top=top*b.bottom; a.bottom=bottom*b.top; a.show(); } void Fraction::compare(Fraction &b,Fraction &c) { double m,n; m=b.top/b.bottom; n=c.top/c.bottom; if(m<n) { cout <<b.top<<'/'<<b.bottom<<'<';c.show();cout<<endl; } else if(m==n) { cout <<b.top<<'/'<<b.bottom<<'=';c.show();cout<<endl; } else { cout <<b.top<<'/'<<b.bottom<<'>';c.show();cout<<endl; } }
Fraction c(5); cout<<"a:",a.show(); cout<<"b:",b.show(); cout<<"c:",c.show(); int x1,y1,x2,y2; cout<<"输入第一个分数的分子分母" <<endl; cin>>x1>>y1; Fraction a1(x1,y1); cout<<"输入第二个分数的分子分母" <<endl; cin>>x2>>y2; Fraction a2(x2,y2); a.add(a1,a2); cout<<"和:",a.show(); a.sub(a1,a2); cout<<"差:",a.show(); a.mul(a1,a2); cout<<"积:",a.show(); a.div(a1,a2); cout<<"商:",a.show(); a.compare(a1,a2); return 0; }