在下一个代码中,我可以输入一个数字 n ,旁边我可以输入 n 对与操作员的数字。
输入
4
1 2 +
3 2 -
4 6 *
2 1 .
对意味着 - > 分子和分母 - > n / d
最后我们必须输入 ''。'' 字符来执行操作,输出应为:
输出
13/3
问题是我无法找到一种方法将数字存储为向量中的对象,进行操作并打印所需的结果。
#include<iostream>
#include <stdio.h>
#include <vector>
using namespace std;
class rational
{
int n,d;
public:
rational() : n(1), d(1) {};
~rational(){};
void setn(int nn){ n = nn;}
void setd(int dn) { d = dn; }
void getData()
{
cin>>n;
cin>>d;
while(d==0)
{
break;
}
while(d<0)
{
n *= -1;
d *= -1;
}
}
int GCD(int n1, int remainder)
{
if(remainder==0)
return(n1);
else { return(GCD(remainder,n1%remainder)); }
}
void printoper()
{
cout << n << " " << d << endl;
}
void reduce(int &n,int &d)
{
int rdc = 0;
if(d>n)
rdc = GCD(d,n);
else if(d<n)
rdc = GCD(n,d);
else
rdc = GCD(n,d);
n /= rdc;
d /= rdc;
cout<<n<<"/"<<d<<endl;
}
void operator +(rational c1)
{
rational temp;
temp.n=(n*c1.d)+(c1.n*d);
temp.d=c1.d*d;
reduce(temp.n,temp.d);
}
void operator -(rational c1)
{
rational temp;
temp.n=(n*c1.d)-(c1.n*c1.d);
temp.d=c1.d*d;
reduce(temp.n,temp.d);
}
void operator *(rational c1)
{
rational temp;
temp.n=n*c1.n;
temp.d=d*c1.d;
reduce(temp.n,temp.d);
}
void operator /(rational c1)
{
rational temp;
temp.n=n*c1.d;
temp.d=d*c1.n;
if(temp.d<0)
{
temp.n *= -1;
temp.d *= -1;
}
reduce(temp.n,temp.d);
}
};
int main()
{
vector<rational> list;
int n;
int d;
rational *p1;
int x;
char cr;
cin>>x;
for(int contador=0; contador<x; contador++){
if(contador<x){
cin>>n;
cin>>d;
cin>>cr;
p1=new rational;
list.push_back(*p1);
cin.get();
}
}
vector<rational>::iterator it;
for ( it = list.begin(); it != list.end(); ++it ) {
it->printoper();
}
cin.get();
return 0;
}
我将不胜感激。
EDITED
I've modified my code to:
#include<iostream>
#include<stdio.h>
using namespace std;
class rational
{
int n,d;
public:
rational() : n(1), d(1) {};
~rational(){};
void getData()
{
cout<<"\nEnter a numerator: ";
cin>>n;
cout<<"Enter a denominator: ";
cin>>d;
cout<<endl;
while(d==0)
{
cout<<"Please enter a denominator: ";
cin>>d;
}
while(d<0)
{
n *= -1;
d *= -1;
}
}
int GCD(int n1, int remainder)
{
if(remainder==0)
return(n1);
else { return(GCD(remainder,n1%remainder)); }
}
void reduce(int &n,int &d)
{
int rdc = 0;
if(d>n)
rdc = GCD(d,n);
else if(d<n)
rdc = GCD(n,d);
else
rdc = GCD(n,d);
n /= rdc;
d /= rdc;
cout<<n<<"/"<<d<<endl;
}
void operator +(rational c1)
{
rational temp;
temp.n=(n*c1.d)+(c1.n*d);
temp.d=c1.d*d;
reduce(temp.n,temp.d);
}
void operator -(rational c1)
{
rational temp;
temp.n=(n*c1.d)-(c1.n*c1.d);
temp.d=c1.d*d;
reduce(temp.n,temp.d);
}
void operator *(rational c1)
{
rational temp;
temp.n=n*c1.n;
temp.d=d*c1.d;
reduce(temp.n,temp.d);
}
};
int main()
{
rational c1, c2;
int n,x;
char cr;
cin>>x;
for(int contador=0; contador<x; contador++){
if(contador<x){
c1.getData();
c2.getData ();
}
}
cin>>cr;
switch(cr)
{
case '+':
c1+c2;
cin.get();
return 0;
case '-':
c1-c2;
cin.get();
return 0;
case '*':
c1*c2;
cin.get();
return 0;
default:
cout<<endl;
return 0;
}
cin.get();
return 0;
}
现在我无法找到一种方法来执行 n 分数 (n / d) 的操作