实验四
一、补全实验四中代码
1 void Graph::draw() { 2 int i, j; 3 for (i = 1; i <= size; i++) 4 { 5 for (j = 1; j <= size - i; j++) 6 cout << " "; 7 for (j = 1; j <= 2 * i - 1; j++) 8 cout << symbol; 9 cout << endl; 10 } 11 }
输出结果
二、设计构造一个函数Fraction,实现分数间加减乘除运算。
//Fraction.h class Fraction { private: int x; int y; public: Fraction(int a = 0, int b = 1) :x(a), y(b) {} friend istream & operator>> (istream& input, Fraction &f); bool operator ==(int a); void output(); Fraction operator -(Fraction &f1); Fraction operator /(Fraction &f1); };
//Fraction.cpp #include <iostream> #include "Fraction.h" #include "stdafx.h" using namespace std; istream& operator>>(istream& input, Fraction &f) { input >> f.x >> f.y; return input; } bool Fraction::operator==(int a) { if (x == a) return true; else return false; } Fraction Fraction::operator -(Fraction &f1) { Fraction f; f.x = x * f1.y - f1.x*y; f.y = y * f1.y; return f; } Fraction Fraction::operator /(Fraction &f1) { Fraction f; if (!f1.x) return *this; f.x = x * f1.y; f.y = y * f1.x; return f; } void Fraction::output() { int r, m = x, n = y, t; if (m<n) { t = n; n = m; n = t; } while (n != 0) { r = m % n; m = n; n = r; } if (y == m) cout << x / m; else if (x / m<0 && y / m<0) cout << (-1)*x / m << '/' << (-1)*y / m; else if (y / m<0) cout << -x / m << '/' << -y / m; else cout << x / m << '/' << y / m; }
1 //main.cpp 2 #include "stdafx.h" 3 #include <iostream> 4 #include "Fraction.h" 5 using namespace std; 6 7 8 int main() 9 { 10 Fraction f1, f2, f3; 11 while (cin >> f1 >> f2) 12 { 13 if (f1 == 0 && f2 == 0) 14 break; 15 f3 = f1 - f2; 16 f3.output(); 17 cout << " "; 18 f3 = f1 / f2; 19 f3.output(); 20 cout << endl; 21 } 22 return 0; 23 }
基本思路是定义分数间的四则运算符号来实现四则运算,可是运行时出现错误 无法解决 请求各位大佬帮助
本人对于定义运算符号掌握地不是很全面,想问下friend 和bool是在什么情况下使用的。