1. 程式人生 > >實驗4

實驗4

pdf compare multipl else pri otto pac mage font

 1.實驗內容2

  (1)size代表行數,i為當前行,j用來控制要輸出的空格,k用來控制要輸出的符號的個數,用for循環逐行輸出

  (2)

#ifndef GRAPH_H
#define GRAPH_H

// 類Graph的聲明 
class Graph {
    public:
        Graph(char ch, int n);   // 帶有參數的構造函數 
        void draw();     // 繪制圖形 
    private:
        char symbol;
        int size;
};


#endif
// 類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, k, s; for (i = 1; i<=size; i++) { for
(j = 1; j<=size - i; j++) { cout << ; } s = 1+2 * (i- 1); for (k = 1; k<= s; k++) { cout << symbol; } cout << endl; } // 補足代碼,實現「實驗4.pdf」文檔中展示的圖形樣式 }
#include <iostream>
#include 
"graph.h" using namespace std; int main() { Graph graph1(*,5), graph2($,7) ; // 定義Graph類對象graph1, graph2 graph1.draw(); // 通過對象graph1調用公共接口draw()在屏幕上繪制圖形 graph2.draw(); // 通過對象graph2調用公共接口draw()在屏幕上繪制圖形 return 0; }

  (3)運行環境:vs2017

    技術分享圖片

  2.實驗內容3

class Fraction {
public:
    Fraction();
    Fraction(int a);
    Fraction(int a, int b);
    void plus(Fraction &p);
    void minus(Fraction &p);
    void multiply(Fraction &p);
    void divide(Fraction &p);
    void compare(Fraction &p);
    void output();
private:
    int top;
    int bottom;

};
#include <iostream>
#include "fraction.h"
using namespace std;


Fraction::Fraction()  {
    top = 0;
    bottom = 1;
}
Fraction::Fraction(int a) {
    top = a;
    bottom = 1;
}
Fraction::Fraction(int a, int b) {
    top = a;
    bottom = b;
}

void Fraction::plus(Fraction &p) {
    top = p.top*bottom + p.bottom*top;
    bottom = p.bottom*bottom;
    output();
}
void Fraction::minus(Fraction &p) {
    top = p.top*bottom - p.bottom*top;
    bottom = p.bottom*bottom;
    output();
}
void Fraction::multiply(Fraction &p) {
    top = p.top*top;
    bottom = p.bottom*bottom;
    output();
}
void Fraction::divide(Fraction &p) {
    top = p.top*bottom;
    bottom = p.bottom*top;
    output();
}
void Fraction::compare(Fraction &p) {
    if (p.top / p.bottom > top / bottom)
        cout << "t>b" << endl;
    else if (p.top / p.bottom < top / bottom)
        cout << "t<b" << endl;
    else if (p.top / p.bottom == top / bottom)
        cout << "t=b" << endl;
}
void Fraction::output() {
        cout << "The result is:"<< top << / << bottom << endl;
    }
#include <iostream>
#include "fraction.h"
using namespace std;

int main() {
    Fraction a;
    Fraction b(3, 4);
    Fraction c(5);
    Fraction d;
    d.plus(b);
    d.output();
    d.minus(b);
    d.output();
    d.multiply(b);
    d.output();
    d.divide(b);
    d.output();
    d.compare(b);
    return 0;
}

運行結果截圖:技術分享圖片

實驗4