我想为使用类的分数创建一个四个函数(+, - ,/,*)计算器。getinf函数有问题,每当我调用它时,它总是在main函数中返回相同的值。我无法弄清楚造成这种情况的原因。
#include<iostream>
#include<conio.h>
#include<cmath>
#include<process.h>
using namespace std;
class frac{
long num,dum;
public:
void getinf(){
cout<<"Enter the fraction = ";
cin>>num>>dum;
if(cin.fail()) {
cout<<"Invalid data entered. "<<"\nTry again. ";getch();exit(0);
}
}
frac add(frac f1,frac f2){
frac f3;
f3.num=((f1.num*f2.dum)+(f1.dum*f2.dum));
f3.dum=f1.dum*f2.dum;
return f3;
}
frac sub(frac f1,frac f2){
frac f3;
f3.num=((f2.num*f2.dum)-(f1.dum*f2.dum));
f3.dum=f1.dum*f2.dum;
return f3;
}
frac mul(frac f1,frac f2){
frac f3;
f3.num=f1.num*f2.num;
f3.dum=f1.dum*f2.dum;
return f3;
}
frac div(frac f1,frac f2){
frac f3;
f3.num=f1.num*f2.dum;
f3.dum=f1.dum*f2.num;
return f3;
}
void lowterm(){
long tnum,tdum,temp,gcd;
tnum=labs(num);
tdum=labs(dum);
if(tdum==0) {
cout<<"Illegal fraction division by 0";exit(1);
} else if(tnum==0) {
num=0;dum=1;return;
}
while(tnum!=0){
if(tnum<tdum) {
temp=tnum;tnum=tdum;tdum=temp;
}
tnum=tnum-tdum;
}
gcd=tdum;
num=num/gcd;
dum=dum/gcd;
}
void showinf(){
cout <<"The result is "<<num<<"/"<<dum;getch();
}
};
void main(){
frac s1,s2,s3;char ch = 'a' ;
s1.getinf();
s2.getinf();
cout<<"Enter the function you want to perform on the fractions (+,-,*,/): ";
cin>>ch;
if(cin.fail()){
cout<<"Invalid operation entered. "<<"\nNo such operation exist. " <<"\nTry again. ";
getch();
exit(0);
}
switch(ch){
case'+':s3.add(s1,s2);break;
case'-':s3.sub(s1,s2);break;
case'*':s3.mul(s1,s2);break;
case'/':s3.div(s1,s2);break;
default:cout<<"Wrong information entered. "<<"\nTry again. ";
}
s3.lowterm();
s3.showinf();
getch();
}
答案 0 :(得分:0)
查看“运营商”功能,例如:
frac mul(frac f1,frac f2){
frac f3;
f3.num=f1.num*f2.dum;
f3.dum=f1.dum*f2.num;
return f3;
}
此功能:
frac
f3
对象
num
和dum
成员特别是,它没有设置this
的{{1}}或num
成员。
当你在main中调用dum
时,你会完全忽略s3.mul(...)
的返回值。由于mul
除了对其返回的对象进行操作之外没有做任何其他操作,因此该调用基本上是无操作。
您应该更改运算符函数,以便它们实际更改对象的字段,如下所示:
mul
或者让它们成为自由函数(或静态成员),并用以下内容调用它们:
void mul(frac f1,frac f2){
num=f1.num*f2.dum;
dum=f1.dum*f2.num;
}
(另请注意,您的frac result = mul(s1, s2); // or frac::mul(s1, s2) for a static member
函数与div
函数具有相同的代码,这可能是一个错误。)
答案 1 :(得分:0)
只需将开关块更改为:
switch(ch){
case'+':s3=s3.add(s1,s2);break;
case'-':s3=s3.sub(s1,s2);break;
case'*':s3=s3.mul(s1,s2);break;
case'/':s3=s3.div(s1,s2);break;
default:cout<<"Wrong information entered. "<<"\nTry again. ";
你的代码没问题。