the problem of using class to define a fraction caculator

hey guys, I got a little problem when running the following code, it is about fraction computation. I dont know why it can't output the result I needed, could anybody help?

#include <iostream>
#include <string>
using namespace std;

class Fraction
{
private:
int top; //Numerator
int bottom; //Denominator
Fraction F1();
Fraction F2();
public:
Fraction() //default constructor
{
top = 0;
bottom = 1;
}
Fraction(int T, int B) //constructor with both numerator and denominator
{
top = T;
if (B==0)
{
cout<<"Invalid number"<<endl;
exit(0);
}
else
bottom = B;
}

Fraction add(Fraction F1, Fraction F2) //peform addition
{
int T = F1.top*F2.bottom+F1.bottom*F2.top;
int B = F1.bottom*F2.bottom;
return Fraction( T, B);
}
Fraction subtract(Fraction F1, Fraction F2) //perform subtraction
{
int T = F1.top*F2.bottom-F1.bottom*F2.top;
int B = F1.bottom*F2.bottom;
return Fraction( T, B);
}
Fraction multiple(Fraction F1, Fraction F2) //perform multiplication
{
int T = F1.top*F2.top;
int B = F1.bottom*F2.bottom;
return Fraction( T, B);
}
Fraction divide(Fraction F1, Fraction F2) //perform division
{
int T = F1.top*F2.bottom;
int B = F1.bottom*F2.top;
return Fraction( T, B);
}
void compare(Fraction F1, Fraction F2) //perform comparasion
{
if (F1.top*F2.bottom<F2.top*F1.bottom)
cout<<"The first fraction is smaller"<<endl;
if (F1.top*F2.bottom==F2.top*F1.bottom)
cout<<"The two fractions are equal"<<endl;
if (F1.top*F2.bottom>F2.top*F1.bottom)
cout<<"The first fraction is greater"<<endl;
}
void input() //Input function
{
cout<<"Please enter the numerator:"<<endl;
cin>>top;
cout<<"Please enter the denominator:"<<endl;
cin>>bottom;
}
void output() //Output function
{
if (bottom == 1)
cout<< top << endl;
else
cout << top << "/" << bottom <<endl;
}
};


int main()
{
Fraction result;
Fraction a;
Fraction b;
int choice;
cout<<"Please enter two fractions"<<endl;
a.input();
b.input();
cout<<"*******************************"<<endl;
cout<<"* Chose one number to continue*"<<endl;
cout<<"* 1.Add *"<<endl;
cout<<"* 2.Subtract *"<<endl;
cout<<"* 3.Multiply *"<<endl;
cout<<"* 4.Division *"<<endl;
cout<<"* 5.Compare *"<<endl;
cout<<"* other keys to exit *"<<endl;
cout<<"*******************************"<<endl;
cin>>choice;
switch(choice)
{
case '1':
result.add(a,b);
result.output();
break;
case '2':
result.subtract(a,b);
result.output();
break;
case '3':
result.multiple(a,b);
result.output();
break;
case '4':
result.divide(a,b);
result.output();
break;
case '5':
result.compare(a,b);
break;
default:
break;
}
return 0;
}
You have two problems. The first one, your "choice" variable needs to be a char, not an int

The second problem, you are not stopping the window from closing. Here's a simple way to solve it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

int main(){

char hold_window;
/*
some code
*/


cin>>hold_window;
return 0;
}

Topic archived. No new replies allowed.