#include <iostream>
using namespace std;
class Fraction {
private:
int num;
int denom;
public:
Fraction() {
int num = 0;
int denom = 1;
}
Fraction(const Fraction& ref) {
num = ref.num;
denom = ref.denom;
}
Fraction(int arg) {
num = arg;
denom = 1;
}
Fraction(int arg, int arg2) {
num = arg;
if (arg2 == 0)
denom = 1;
else
denom = arg2;
}
~Fraction() {
}
void setnum(int arg) {
num = arg;
return;
}
void setdenom(int arg) {
if(arg) {
denom = arg;
} else {
denom = 1;
}
return;
}
int getnum() const {
return num;
}
int getdenom() const {
return denom;
}
};
Fraction addition(Fraction&, Fraction&);
Fraction init(void);
void print(Fraction&);
void menu(void);
int main() {
menu();
return 0;
}
void menu() {
int option;
Fraction e;
Fraction f;
Fraction g;
cout << "option: ";
cin >> option;
do {
switch(option) {
case 1:
cout << "For init: " << endl;
e = init();
f = init();
menu();
break;
case 2:
cout << "For add: " << endl;
g = addition(e,f);
break;
case 3:
cout << "For print: " << endl;
print(g);
break;
case 4:
cout << "bb" << endl;
break;
default:
cout << "Wrong" << endl;
}
}while(option != 4);
return;
}
Fraction addition(Fraction& arg1, Fraction& arg2) {
Fraction temp;
temp.setnum((arg1.getnum() * arg2.getdenom()) + (arg1.getdenom() * arg2.getnum()));
temp.setdenom(arg1.getdenom() * arg2.getdenom());
return temp;
}
Fraction init() {
int num;
int denom;
cout << "num: ";
cin >> num;
cout << "denom: ";
cin >> denom;
Fraction info(num, denom);
return info;
}
void print(Fraction& info) {
cout << "num: " << info.getnum() << endl;
cout << "denom: " << info.getdenom() << endl;
return;
}
我正在制作一个程序来添加两个分数
我有3个选项的菜单:初始化,添加和打印
我的计划是:
首先我选择init选项,然后输入两个分数
然后我将返回菜单并选择添加选项以添加两个分数
最后我选择打印选项打印结果
但是从上面的程序中,我总是遇到init选项
的问题实际上我可以做输入,但是当我回到菜单并进行添加时,
添加无效
我认为它没有用,因为添加功能没有得到输入
所以我想问一下如何解决这个问题?
抱歉我的英语不好
答案 0 :(得分:0)
menu
功能已损坏。它只读取输入一次然后永远循环(除非它是1
或4
)。您应该阅读循环内的option
值。并删除选项1中不必要的递归。
void menu() {
int option;
Fraction e;
Fraction f;
Fraction g;
do {
cout << "option: ";
cin >> option;
switch(option) {
case 1:
cout << "For init: " << endl;
e = init();
f = init();
// menu(); <-- Remove this
break;
case 2:
cout << "For add: " << endl;
g = addition(e,f);
break;
case 3:
cout << "For print: " << endl;
print(g);
break;
case 4:
cout << "bb" << endl;
break;
default:
cout << "Wrong" << endl;
}
}while(option != 4);
return;
}