Server IP : 172.16.15.8 / Your IP : 3.15.203.242 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/jwang/ |
[ Home ] | [ C0mmand ] | [ Upload File ] |
---|
// CS 212 Assignment 4 // // Filename: hw4.cpp // // Author: Nathan Lutz // // Instructor: Dr. Wang // Due: Feb 27, 2008 // Compile: g++ hw4.cpp -o a.out // Run: ./a.out // Purpose: write a program to read two fractions and an operator +, -, *, or /, perform the operation, output the result. #include <iostream> using namespace std; class Fraction { int num, den; public: Fraction() // Default 0/1 { num=0; den=1; } Fraction(int n, int d) { num=n; den=d; } void Set(int n, int d) { num=n; den=d; } void Print() const { cout<<num<<"/"<<den; } Fraction Add (Fraction x) { Fraction answer; int n,d; d = Fraction :: den * x.den; n = num * x.den + den*x.num; answer.Set(n,d); return answer; } Fraction Sub (Fraction x) { Fraction answer; int n,d; d = Fraction :: den * x.den; n = num * x.den - den*x.num; answer.Set(n,d); return answer; } Fraction Mult (Fraction x) { Fraction answer; int n,d; n = num*x.num; d = den*x.den; answer.Set(n,d); return answer; } Fraction Div (Fraction x) { Fraction answer; int n,d; n = num/x.num; d = den/x.den; answer.Set(n,d); return answer; } }; int main() { int nu,de; char dummy,op; Fraction x,y,z; cout<<"Input x: (-1/1 to quit) "<<endl; cin>>nu>>dummy>>de; while (nu!=-1 && de!=1) { x.Set(nu,de); cout<<"Input y: "<<endl; cin>>nu>>dummy>>de; y.Set(nu,de); cout<<"Input the operation: "<<endl; cin>>op; if (op=='+') { z=x.Add(y); x.Print(); cout<<" + "; y.Print(); cout<<" = "; z.Print(); } else if (op=='-') { z=x.Sub(y); x.Print(); cout<<" - "; y.Print(); cout<<" = "; z.Print(); } else if (op=='*') { z=x.Mult(y); x.Print(); cout<<" * "; y.Print(); cout<<" = "; z.Print(); } else if (op=='/') { z=x.Div(y); x.Print(); cout<<" / "; y.Print(); cout<<" = "; z.Print(); } else cout<<"This is not a valid operation."<<endl; cout<<"\nInput x: (-1/1 to quit)"<<endl; cin>>nu>>dummy>>de; } cout<<"\n\nThank you."<<endl; return 0; } ****************************************************************************************************************** Output: [ndlutz@zeus CS212]$ ./a.out Input x: (-1/1 to quit) 1/3 Input y: 1/2 Input the operation: * 1/3 * 1/2 = 1/6 Input x: (-1/1 to quit) 1/2 Input y: 1/2 Input the operation: + 1/2 + 1/2 = 4/4 Input x: (-1/1 to quit) -1/1 Thank you