#include <iostream>
using namespace std;
class Fraction {
private:
int num;
int denom;
public:
Fraction() {
num = 0;
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;
}
};
int main() {
menu();
return 0;
}
Fraction::Fraction add(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::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;
}
void menu() {
int option;
do {
cout << "Select an option (use integer value only): ";
cin >> option;
switch(option) {
case 1:
initializingMenu();
break;
case 2:
addingMenu();
break;
case 3:
printingMenu();
break;
case 4:
cout << "Have Fun!" << endl;
break;
default:
cout << "Wrong option!" << endl;
}
} while (option != 0);
return;
}
void initializingMenu() {
Fraction a;
Fraction b;
Fraction c;
int option;
do {
cout << "Select an option (1, 2, or 3): ";
cin >> option;
switch(option) {
case 1:
cout << "\nCalling init() - Stand Alone...\n" << endl;
a = init();
b = init();
break;
case 2:
menu();
break;
default:
cout << "\nWrong option!" << endl;
initializingMenu();
}
} while (option != 0);
return;
}
void addingMenu() {
Fraction a;
Fraction b;
Fraction c;
int option;
do {
cout << "Select an option (1, 2, 3 or 4): ";
cin >> option;
switch(option) {
case 1:
cout << "\nCalling add() - Stand Alone...\n" << endl;
c = add(a,b);
break;
case 2:
menu();
break;
default:
cout << "\nWrong option!" << endl;
addingMenu();
}
} while (option != 0);
return;
}
void printingMenu() {
Fraction a;
Fraction b;
Fraction c;
int option;
do {
cout << "Select an option (1, 2, or 3): ";
cin >> option;
switch(option) {
case 1:
cout << "\nCalling print() - Stand Alone...\n" << endl;
print(c);
break;
case 2:
menu();
break;
default:
cout << "\nWrong option!" << endl;
printingMenu();
}
} while (option != 0);
return;
}
我正在制作一个将两个分数相加的程序
我正在尝试使用菜单来做到这一点
我有四个菜单:
主菜单:提供进入其他菜单的选项
初始化菜单:输入 num 和 denom
添加菜单:添加分数
打印菜单:打印添加的分数
麻烦:所以我运行程序并按顺序浏览菜单: main > init > add > print 但是当我打印时,结果是错误的,例如,1/2 和 1/2 假设给我 2/2 但是当我打印,它给我 0/1,这是默认构造函数
我有另一个程序,它可以工作: 添加两个分数
从网站上的程序来看,我认为它有效,因为我将它们放在同一个菜单中,但对于这个,我认为是因为我分开了,所以打印没有从类中获得 num 和 denom 值
所以我想问,我该如何解决这个问题?以及为什么当我用菜单将它们分开时我无法得到真正的结果
对不起我的英语不好和这么多代码