要求功课。我不明白错误在哪里...您能对我的代码说些什么?
有必要在方法main()中执行计算。为了计算除法的最小余数,我使用了欧几里得算法(迭代)。
进一步进行分数运算。据我了解,减少分数时会发生错误。
预先感谢您的帮助。
#include <iostream>
using namespace std;
class Fraction {
private:
int a; // числитель
int b; // знаменатель
//алгоритм Евклида (итерационный)
int nod(int x, int y) {
while (x != y) {
if (x > y) {
long tmp = x;
x = y;
y = tmp;
}
y = y - x;
}
return x;
}
public:
void Show() {
cout << this->a << "/" << this->b;
}
// конструктор по умолчанию (числитель = 0, знаменатель = 1)
Fraction() {
this->a = 0; this->b = 1;
}
// конструктор с заданным числителем x и знаменателем y
Fraction(int x, int y) {
if (y != 0) {
this->a = x; this->b = y;
}
else cout << "Error" << endl;
}
// Методы для свойства - числитель
void setNumerator(int x) {
this->a = x;
}
int getNumerator() {
return this->a;
}
//Методы для свойства числитель
void setDeNumerator(int x) {
if (x == 0) printf("Delenie ne nol!\n");
else this->b = x;
}
int getDeNumerator() {
return this->a;
}
void Irreducible() {
int node = nod(this->a, this->b); // НОд числителя и знаменателя
this->a / node;
this->b / node;
}
};
Fraction operator+(Fraction & x, Fraction & y) {
Fraction c;
c.setNumerator(x.getNumerator() * y.getDeNumerator() + x.getDeNumerator() * y.getNumerator());
c.setDeNumerator(x.getDeNumerator() * y.getDeNumerator());
c.Irreducible();
return c;
}
Fraction operator-(Fraction & x, Fraction & y) {
Fraction c;
c.setNumerator(x.getNumerator() * y.getDeNumerator() - x.getDeNumerator() * y.getNumerator());
c.setDeNumerator(x.getDeNumerator() * y.getDeNumerator());
c.Irreducible();
return c;
}
Fraction operator*(Fraction & x, Fraction & y) {
Fraction c;
c.setNumerator(x.getNumerator() * y.getNumerator());
c.setDeNumerator(x.getDeNumerator() * y.getDeNumerator());
c.Irreducible();
return c;
}
Fraction operator/(Fraction & x, Fraction & y) {
Fraction c;
c.setNumerator(x.getNumerator() * y.getDeNumerator());
c.setDeNumerator(x.getDeNumerator() * y.getNumerator());
c.Irreducible();
return c;
}
int main() {
int ch, zn;
cout << "chis1="; cin >> ch;
cout << "znam1="; cin >> zn;
Fraction f1(ch, zn);
cout << "chis2="; cin >> ch;
cout << "znam2="; cin >> zn;
Fraction f2(ch, zn);
Fraction sum = f1 + f2;
f1.Show(); cout << "+"; f2.Show(); cout << " ="; sum.Show(); cout << endl;
Fraction raz = f1 - f2;
f1.Show(); cout << "-"; f2.Show(); cout << " ="; raz.Show(); cout << endl;
Fraction pro = f1 * f2;
f1.Show(); cout << "*"; f2.Show(); cout << " ="; pro.Show(); cout << endl;
Fraction div = f1 / f2;
f1.Show(); cout << "/"; f2.Show(); cout << " ="; div.Show(); cout << endl;
system("pause");
return 0;
}
答案 0 :(得分:-1)
需要将this->a / node
替换为this->a /= node