Server IP : 172.16.15.8 / Your IP : 3.145.57.41 Web Server : Apache System : Linux zeus.vwu.edu 4.18.0-553.27.1.el8_10.x86_64 #1 SMP Wed Nov 6 14:29:02 UTC 2024 x86_64 User : apache ( 48) PHP Version : 7.2.24 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON Directory (0705) : /home/kebuck/ |
[ Home ] | [ C0mmand ] | [ Upload File ] |
---|
// CS 212 Computer Programming II Assignment 3 // Due: Monday February 28, 2011 // // File: homework2.cpp // Author: Katie Buck // Instructor: Dr. Wang // // Compile: g++ homework3.cpp // Run: ./a.out < fractions.txt > out3.txt // // Goal: The goal of this program is to define a Fraction class // that contains the function members and be able to add, // subtract, divide, and reduce fractions. #include <iostream> using namespace std; class Fraction { int nume; int deno; Fraction reduce () { int n = nume; int d = deno; while ( d != 0) { int r = n%d; n = d; d = r; } if ( n != 0) { nume /= n; deno /= n; } if (deno < 0) { nume *= (-1); deno *= (-1); } } public: Fraction() { nume = 0; deno = 1; } Fraction(int n, int d) { nume = n; deno = d; } void Set(int n, int d) { nume = n; deno = d; } void Print() const { cout << nume << "/" << deno; } Fraction operator+(Fraction x) { Fraction ans; ans.nume = nume * x.deno + deno * x.nume; ans.deno = deno * x.deno; // use the reduce() ans.reduce(); return ans; } Fraction operator-(Fraction x) { Fraction ans; ans.nume = nume * x.deno - deno * x.nume; ans.deno = deno * x.deno; ans.reduce(); return ans; } Fraction operator*(Fraction x) { Fraction ans; ans.nume = nume * x.nume; ans.deno = deno * x.deno; ans.reduce(); return ans; } Fraction operator/(Fraction x) { Fraction ans; ans.nume = nume * x.deno; ans.deno = deno * x.nume; ans.reduce(); return ans; } }; int main() { int a1, b1; int a2, b2; char dummy, op; while(cin) { cin >> a1 >> dummy >> b1; cin >> op; cin >> a2 >> dummy >> b2; Fraction f1, f2, answ; f1.Set(a1, b1); f2.Set(a2, b2); if(op == '+') answ = f1 + f2; if(op == '-') answ = f1 - f2; if(op == '*') answ = f1 * f2; if(op == '/') answ = f1 / f2; f1.Print(); cout << " " << op << " "; f2.Print(); cout << " = "; answ.Print(); cout << "\n"; } return 0; }