代码改变世界

实验三

2019-04-21 17:37  Chirly  阅读(117)  评论(0编辑  收藏  举报

Part 2

#include <iostream>
#include "graph.h"
using namespace std;
int main() {
    Graph graph1('*',5);
    graph1.draw();
    
    system("pause");
    system("cls");
    
    Graph graph2('$',7);
    graph2.draw();
    system("pause");
    
    return 0; 
} 
main
#include "graph.h" 
#include <iostream>
using namespace std;

// 带参数的构造函数的实现 
Graph::Graph(char ch, int n): symbol(ch), size(n) {
}


// 成员函数draw()的实现
// 功能:绘制size行,显示字符为symbol的指定图形样式 
void Graph::draw() {
    int i, j, k;
    for(i=1;i<=size;i++)
    {
        for (j = 1; j <= size - i; j++)
            cout << " ";
        for (k = 1; k <= 2 * i - 1; k++)
            cout << symbol;
        cout << endl;

    }
}
graph
#ifndef GRAPH_H
#define GRAPH_H

// 类Graph的声明 
class Graph {
    public:
        Graph(char ch, int n);   // 带有参数的构造函数 
        void draw();     // 绘制图形 
    private:
        char symbol;
        int size;
};

#endif
graph.h

运行结果:

 

 

 

Part 3

#include<iostream>
#include"Fraction.h"
using namespace std;
int main(){
    fraction a;
    a.show();
    fraction b(3,4);
    b.show();
    fraction c(5);
    c.show();
    fraction d;
    d.add(b,c);
    d.min(b,c);
    d.mul(b,c);
    d.div(b,c);
    d.com(b,c);
}
main
#include "fraction.h"
#include<iostream>
using namespace std;

void fraction::add(fraction a , fraction b){
    fraction c;
    c.top=a.top*b.bottom+b.top*a.bottom;
    c.bottom=a.bottom*b.bottom;
    cout<<"两数相加:"<<c.top<<"/"<<c.bottom<<endl;
}

void fraction::min(fraction a , fraction b){
    fraction c;
    c.top=a.top*b.bottom-b.top*a.bottom;
    c.bottom=a.bottom*b.bottom;
    cout<<"两数相减:"<<c.top<<"/"<<c.bottom<<endl;
}

void fraction::mul(fraction a , fraction b){
    fraction c;
    c.top=a.top*b.top;
    c.bottom=a.bottom*b.bottom;
    cout<<"两数相乘:"<<c.top<<"/"<<c.bottom<<endl;
}

void fraction::div(fraction a , fraction b){
    fraction c;
    c.top=a.top*b.bottom;
    c.bottom=a.bottom*b.top;
    cout<<"两数相除:"<<c.top<<"/"<<c.bottom<<endl;
}

void fraction::com(fraction a , fraction b){
    int c;
    c=a.top*b.bottom-b.top*a.bottom;
    if (c<0)
    cout<<"两数相较:"<<a.top<<"/"<<a.bottom<<"<"<<b.top<<"/"<<b.bottom<<endl;
        else if (c>0)
        cout<<"两数相较:"<<a.top<<"/"<<a.bottom<<">"<<b.top<<"/"<<b.bottom<<endl;
            else
            cout<<"两数相较:"<<a.top<<"/"<<a.bottom<<"="<<b.top<<"/"<<b.bottom<<endl;
}

void fraction::show(){
    cout<<top<<"/"<<bottom<<endl;
}
fraction
#ifndef FRACTION_H
#define FRACTION_H
class fraction{
    public:
        fraction(int top0 = 0 , int bottom0 = 1):top(top0),bottom(bottom0){}
        void add(fraction a,fraction b);
        void min(fraction a,fraction b);
        void mul(fraction a,fraction b);
        void div(fraction a,fraction b);
        void com(fraction a,fraction b);
        void show();
    private:
        int top;
        int bottom;
};

#endif
fraction.h

运行结果: