我刚刚在学习 C++,并且有一项作业必须将事物输出为分数。我从来没有在 C++ 中工作过,所以我不太确定我这样做是否正确。我的程序让我输入前两个分数,然后它崩溃了(我假设这与我的功能以及我如何在 int main 中实现它们有关)我通常会去找导师,但不幸的是我去的学校不提供这门课的导师,而且我是从一个教C的学校转过来的,所以我真的很挣扎!非常感谢任何帮助(:
#include<iostream>
using namespace std;
class gcd
{
public:
void finder();
void rename();
void add();
void subtract();
void multiply();
void divide();
void print();
private:
int n, d, n1, d1, temp1, temp2;
} g1;
void gcd::finder()
{
temp1 = n;
temp2 = d;
while (n != d)
{
if (n > d)
n = n - d;
else
d = d - n;
}
n1 = temp1 / n;
d1 = temp2 / d;
}
void gcd::rename()
{
n1 = n;
d1 = d;
}
void gcd::add()
{
n1 = (n1 * d) + (n * d1);
d1 = (d1 * d);
g1.finder();
}
void gcd::subtract()
{
n1 = (n1 * d) - (n * d1);
d1 = (d1 * d);
g1.finder();
}
void gcd::multiply()
{
n1 = n * n1;
d1 = d * d1;
g1.finder();
}
void gcd::divide()
{
n1 = n1 * d;
d1 = d1 * n;
g1.finder();
}
void gcd::print()
{
cout << n1 << "/" << d1 << endl;
}
int main()
{
int n, d;
cout << "Please enter 5 fractions with a space between the numerator and denominator" << endl;
cout << "For example, input 2/3 as 2 3" << endl;
cout << "Enter 1st fraction: ";
cin >> n >> d;
g1.rename();
cout << "Enter 2nd fraction: ";
cin >> n >> d;
g1.divide();
cout << "Enter 3rd fraction: ";
cin >> n >> d;
g1.multiply();
cout << "Enter 4th fraction: ";
cin >> n >> d;
g1.add();
cout << "Enter 5th fraction: " << endl << endl;
cin >> n >> d;
g1.subtract();
g1.print();
return 0;
}
最佳答案
- 您需要了解什么是 OO 编程、类和构造函数。理想情况下,您的类应该是一个
Fraction
类,具有分子和分母以及运算符重载以执行基本算术和 IO。 - 如果您不知道运算符重载,只需使用类的静态成员函数来执行算术运算即可。
- 如果您不知道静态成员函数,那么您可以创建以下形式的成员函数:
Fraction add(const Fraction& another) const
-> 这会将传递给成员函数的分数作为 another
变量与自身相加并返回一个新分数 没有突变/改变自己。
void add(const Fraction& another)
-> 这会将 another
分数添加到自身(从而改变自身)。
这是一个例子:
class Fraction
{
int num, den ;
public:
Fraction(int n, int d) : num(n), den(d) {}
Fraction add(const Fraction&) const ;
Fraction sub(const Fraction&) const ;
Fraction mul(const Fraction&) const ;
Fraction div(const Fraction&) const ;
void show() const;
};
Fraction Fraction::add(const Fraction& another) const
{
return Fraction(num*another.den + den*another.num, den*another.den);
}
void Fraction::show() const
{
std::cout << num << "/" << den ;
}
... // define other methods likewise
主要功能:
int main()
{
int n, d ;
std::cout << "Enter first fraction : ";
std::cin >> n >> d ;
Fraction a(n, d);
std::cout << "Enter second fraction : ";
std::cin >> n >> d ;
Fraction b(n, d);
Fraction sum = a.add(b);
std::cout << "Sum is : " ;
sum.show();
}
注意:您还应该尝试编写一个函数来减少分数,即消除分子和分母之间的公因数。
关于c++ - C++初学者(计算和输出分数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32471537/