嘿傢伙開始我會說我已經看過很多類似的程序,然後發佈這個問題,仍然需要一些幫助。我的問題在於添加分數類函數,我需要將一個分數添加到另一個分數。我有一個類,目前正在使用該類的實例(fractionObject和fractionObject2)。我分別存儲我的分數,一個存儲在fractionObject中,另一個存儲在fractionObject2中。我如何在分數類函數'Add'中添加這些?添加分數和類 - Woot
任何提示將不勝感激!謝謝你的時間!
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
// Regular prototypes
int stringToNumber(const string &Text);
int GCD(int, int);
int LCM(int, int);
class fraction{
public: // Access Specifier
int numerator;
int denominator; // Can never be 0
// Function Prototypes
fraction();
void setNumDen();
void reduce();
void add();
};
// Member functions definitions
fraction::fraction()
{
numerator = 0;
denominator = 0;
}
void fraction::setNumDen()
{
string numString;
string denString;
do{
cout << "Enter a numerator and denominator of fraction 1 separated by whitespace: ";
getline(cin, numString, ' ');
getline(cin, denString);
if (denString == "0")
cout << endl << "Please enter a number that isn't zero." << endl;
} while (denString == "0"); // Making sure denominator is not zero
numerator = stringToNumber(numString);
denominator = stringToNumber(denString);
}
void fraction::reduce()
{
int leastCommonMultiple = 0;
leastCommonMultiple = LCM(numerator, denominator);
numerator /= leastCommonMultiple;
denominator /= leastCommonMultiple;
}
void fraction::add()
{
int leastComDen;
}
int main()
{
fraction fractionObject, fractionObject2;
fractionObject.setNumDen();
fractionObject2.setNumDen();
// Reducing and displaying the reduced fractions
fractionObject.reduce();
fractionObject2.reduce();
cout << "Reduced Fraction 1 = " << fractionObject.numerator << "/" << fractionObject.denominator << "\t" << "Reduced Fraction 2 = " << fractionObject2.numerator << "/" << fractionObject2.denominator << endl;
// Adding and displaying the fractions
system("pause");
return 0;
}
// Function to convert string to number
int stringToNumber(const string &Text)//Text not by const reference so that the function can be used with a
{ //character array as argument
stringstream ss(Text);
int result;
return ss >> result ? result : 0;
}
// result=GCD(a,b)
int LCM(int a, int b) {
int temp = 0;
while (b != 0) {
temp = b;
b = a%b;
a = temp;
}
return a;
}
// result=LCM(a,b);
int GCD(int a, int b) {
int result = 0;
result = a * (b/LCM(a, b));
return result;
}
我建議從添加原型開始改變:void add(const fraction&toAdd);傳遞要添加到這個分數的分數。 – user4581301
感謝您的輸入我做到了這一點,我仍然在努力弄清楚! – Drew
請注意,由於您有一種減少方法,因此您無需首先找到最小公分母(因爲您似乎打算這麼做)。只要找到** a **共同倍數(例如兩個分母的乘積),當您完成後,呼叫就會減少。 –