#ifndef GRAPH_H #define GRAPH_H class Graph { public: Graph(char ch, int n); void draw(); private: char symbol; int size; }; #endif
#include "graph.h" #include <iostream> using namespace std; Graph::Graph(char ch, int n): symbol(ch), size(n) { } 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; } }
#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; }
3
#ifndef FRACTION_H
#define FRACTION_H
class Fraction {
public:
Fraction(int x = 0, int y = 1) : top(x), bottom(y) { if (bottom == 0) exit(0); };
void show();
void simplyFraction();
friend Fraction addf(Fraction &a,Fraction &b);
friend Fraction minf(Fraction &a,Fraction &b);
friend Fraction mulf(Fraction &a,Fraction &b);
friend Fraction divf(Fraction &a,Fraction &b);
private:
int top;
int bottom;
};
#endif
fraction.h
#include <iostream> #include "fraction.h" using namespace std; void Fraction::show() { if (bottom < 0) top = -top; if (top == 0) cout << 0 << endl; else if (bottom == 1) cout << top << endl; else cout << top << "/" << bottom << endl; } void Fraction::simplyFraction() { int m=1; for (int i = 2;i <= top&&i <= bottom;i++) { if (top%i == 0 && bottom%i == 0) m = i; } top = top / m; bottom = bottom / m; } Fraction addf(Fraction &a, Fraction &b) { Fraction aresult; aresult.top = a.top*b.bottom + b.top*a.bottom; aresult.bottom = a.bottom*b.bottom; aresult.simplyFraction(); return aresult; } Fraction minf(Fraction &a, Fraction &b) { Fraction minresult; minresult.top = a.top*b.bottom - b.top*a.bottom; minresult.bottom = a.bottom*b.bottom; minresult.simplyFraction(); return minresult; } Fraction mulf(Fraction &a, Fraction &b) { Fraction mulresult; mulresult.top = a.top*b.top; mulresult.bottom = a.bottom*b.bottom; mulresult.simplyFraction(); return mulresult; } Fraction divf(Fraction &a, Fraction &b) { Fraction dresult; dresult.top = a.top*b.bottom; dresult.bottom = a.bottom*b.top; dresult.simplyFraction(); return dresult; }
#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(); addf(a, b).show(); minf(a, c).show(); mulf(b, c).show(); divf(b, c).show(); return 0; }