C++实验四
1.
//complex.h class Complex{ public: Complex(float X,float Y):x(X),y(Y){} Complex(float X):x(X){} void add(Complex &c); void show(); private: float x,y; }; //Complex.cpp #include"Complex.h" #include<iostream> using namespace std; void Complex::add(Complex &c){ x+=c.x; y+=c.y; } void Complex::show(){ cout<<x<<"+"<<y<<"i"<<endl; } #include <iostream> #include"Complex.h" /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { Complex c1(3,5); Complex c2=4.5; c1.add(c2); c1.show(); return 0; }
2.类的定义
//Graph.h class Graph{ public: Graph(char CH,int N):ch(CH),n(N){}//构造函数 void draw();//绘制图形 private: char ch;int n; };
类的实现
//Graph.cpp #include"Graph.h" #include<iostream> using namespace std; void Graph::draw(){ for(int y=1;y<=n;y++)//行 { for(int i=y;i<=n;++i)//空格数 { if(i!=n) cout<<" "; if(i==n) { for(int x=1;x<=2*y-1;++x)//符号个数 cout<<ch; } } cout<<endl; } }
#include <iostream> #include"Graph.h" /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { Graph graph1('*',5); graph1.draw(); Graph graph2('$',7); graph2.draw(); return 0; }
3.(1)
#include<iostream> using namespace std; class Fraction{ public: Fraction(int t=0,int b=1); void show(); private: int top,bot; }; Fraction::Fraction(int t,int b):top(t),bot(b){} void Fraction::show(){ cout<<top<<"/"<<bot<<endl; } int main(){ Fraction a; a.show(); Fraction b(3,4); b.show(); Fraction c(5); c.show(); return 0; }
(2)
#include<iostream> using namespace std; class Fraction{ public: Fraction(int t=0,int b=1); void show(); void jia(Fraction &a); void jian(Fraction &a); void cheng(Fraction &a); void chu(Fraction &a); void bijiao(Fraction &a); private: int top,bot; }; Fraction::Fraction(int t,int b):top(t),bot(b){} void Fraction::show(){ cout<<top<<"/"<<bot<<endl; } void Fraction::jia(Fraction &a){ top=a.top*bot+a.bot*top; bot=a.bot*bot; } void Fraction::jian(Fraction &a){ top= top*a.bot-bot*a.top; bot=a.bot*bot; } void Fraction::cheng(Fraction &a){ top=a.top*top; bot=a.bot*bot; } void Fraction::chu(Fraction &a){ top=top*a.bot; bot=bot*a.top; } void Fraction::bijiao(Fraction &a){ int i=top*a.bot-bot*a.top; if(i>0) cout<<top<<"/"<<bot<<">"<<a.top<<"/"<<a.bot; if(i==0) cout<<top<<"/"<<bot<<"="<<a.top<<"/"<<a.bot; if(i<0) cout<<top<<"/"<<bot<<"<"<<a.top<<"/"<<a.bot; } int main(){ Fraction a; a.show(); Fraction b(3,4); b.show(); Fraction c(5); c.show(); return 0; }