Hey guys to start off I will say that I have looked into a lot of similar programs before posting this question and still need some help. My problem lies in the addition fraction class function where I need to add one fraction to another. I have one class and am currently working with to instances of that class (fractionObject and fractionObject2). I am storing my fractions separately, one in fractionObject and one in fractionObject2. How can I add these in my fraction class function 'Add'?
Any tips will be much appreciated! Thanks for your time!
#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;
}
No complete answer here, but add should have two const fraction& arguments and return a temporary fraction object. You might rename it operator+. Many libraries add a += operator that doesn't require making a temporary object. C++11 allows you to reduce the overhead of these temporary objects with a move constructor.
As for the implementation, here’s a hint: 1/6 + 1/9 = (9+6)/54 = 5/18. I notice you already have a reduce function.
Related
In my simpleClass.cpp file, I have initialized firstNum = 1, and secondNum = 2. Sum has been set to 0. However, when the classObject.getSum() is called in the main function, the sum displayed was 0 instead of 3.
I've tried to remove the sum = '0'; (in the simpleClass.cpp file), but the sum returned will display the memory allocated in the RAM (I suppose).
This is my main.cpp file:
int main() {
// Creating object from the class
simpleClass classObject;
// Expected to print the returned sum which is 3
cout << "The sum of both numbers are: " << classObject.getSum() << endl;
system("pause");
return 0;
}
This is my simpleClass.h file:
#ifndef SIMPLECLASS_H
#define SIMPLECLASS_H
class simpleClass {
public:
simpleClass();
// Setters and getters for firstNum
void setFirstNum(int firstNum);
int getFirstNum() const;
// Setters and getters for secondNum
void setSecondNum(int secondNum);
int getSecondNum() const;
// Setters and getters for sum
void setSum(int firstNum, int secondNum, int sum);
int getSum() const;
private:
int firstNum, secondNum;
int sum;
};
#endif
This is my simpleClass.cpp file:
#include "simpleClass.h"
using namespace std;
simpleClass::simpleClass() {
firstNum = 1;
secondNum = 2;
sum ='\0';
}
// Setters and getters for firstNum
void simpleClass::setFirstNum(int first) {
first = firstNum;
}
int simpleClass::getFirstNum() const {
return firstNum;
}
// Setters and getters for secondNum
void simpleClass::setSecondNum(int second) {
second = secondNum;
}
int simpleClass::getSecondNum() const {
return secondNum;
}
// Setters and getters for sum
void simpleClass::setSum(int first, int second, int s) {
s = first + second;
}
int simpleClass::getSum() const {
return sum;
}
The firstNum and secondNum returned are accurate, except for sum. I'm asking here to get a better understanding of the concept of header and implementation files. Thank you in advance.
I need help containing the data inputted with dollars and cents. I've been trying by putting it in a total_money equation, but I'am stuck. For example, when I deposit 30 dollars I want it to stay there so when I go back in a deposit 10 dollars I get 40.
This is all about depositing and withdrawing money from a bank account while it keeps track of the total money left in the account by using classes.
#include <iostream>
using namespace std;
class SavingsAccount
{
public:
SavingsAccount();
SavingsAccount(int d, int c);
void deposit(int d, int c);
void withdraw(int d, int c);
void total(int d, int c);
void set(int dollars, int cents);
void convert(int d, int c);
private:
double total_money;
int dollars;
int cents;
};
SavingsAccount::SavingsAccount()
{
dollars = 0;
cents = 0;
}
void SavingsAccount::set(int dollars, int cents)
{
}
int main()
{
SavingsAccount bank1, bank2(50, 88);
int dollars, cents;
bank1.set(30, 65);
bank2.set(0, 0);
int anwser;
cout << "Would you like to 1.Deposit or 2.Withdraw?";
cin >> anwser;
if (anwser == 1)
{
cout << "Enter in how much you want to deposit in dollars:";
cin >> dollars;
cout << "Enter in how much you want to deposit in cents:";
cin >> cents;
if (dollars < 0 || cents < 0)
{
cerr << "Invalid!" << endl;
exit(1);
}
bank1.deposit(dollars, cents);//should call upon the seprate deposit funtction below
}
else if (anwser == 2)
{
cout << "Enter in how much you want to withdraw in dollars:";
cin >> dollars;
cout << "Enter in how much you want to withdraw in cents:";
cin >> cents;
if (dollars < 0 || cents < 0)
{
cerr << "Invalid!" << endl;
exit(1);
}
bank1.withdraw(dollars, cents);
}
}
SavingsAccount::SavingsAccount(int d, int c)
{
dollars = d;
cents = c;
}
void SavingsAccount::convert(int d, int c)
{
dollars = dollars + c / 100;
cents = c % 100;//% used for the remainer
}
void SavingsAccount::deposit(int d, int c)
{
dollars += d;//d is where the program keeps track of the values
cents += c;
if (cents >= 100)
{
convert(d, c);
}
//total_money=???
total(dollars, cents);
}
void SavingsAccount::withdraw(int d, int c)
{
dollars += d;
cents += c;
if (cents >= 100)
{
convert(c, d);
}
//total_money=???
total(dollars, cents);
}
void SavingsAccount::total(int d, int c)
{
cout << "Total money: " <<d<<"."<< c<< endl;
}
The code seems to be a little messy and there are some wrong things happening here:
The method set() does nothing.
The field total_money is never initialized, set or queried.
The main() method somehow landed between the implementations of SavingsAccount, which is not a problem but makes your code harder to read.
convert is a non-static member function, so why don't you use the fields dollars and cents directly by first checking for a cent overflow and then modifying them in the overflow case.
In the method deposit(), the member variables are updated as expected. But then, convert() is called with the methods parameters and not with the fields. This will not change dollars or cents in any way (best to implement convert() as described in 4). At the end, you call total() again with the field values, which weren't converted.
The method withdraw() does exactly the same as deposit(). Did you mean to use -=?
total() does nothing else than printing the value. First, this could again be done using the fields instead of parameters (as it is not static), and second, you should rename this method to something like print() and parameterize it with an ostream.
Depending on how you would change your code, some methods may as well be private.
A well-formed program could look like this:
#include<iostream>
using namespace std;
class SavingsAccount {
unsigned int dollars;
unsigned int cents;
double total_money; //actually not necessary
static double getDoubleVal(unsigned int, unsigned int);
void convert();
public:
SavingsAccount();
SavingsAccount(unsigned int, unsigned int);
void setValues(unsigned int, unsigned int);
void deposit(unsigned int, unsigned int);
void withdraw(unsigned int, unsigned int);
ostream& print(ostream&) const;
}
double SavingsAccount::getDoubleVal(unsigned int d, unsigned int c) {
return d + (c / 100.0);
}
void SavingsAccount::convert() {
dollars += cents / 100 //integer divison on purpose
cents %= 100;
total_money = getDoubleVal(dollars, cents);
}
SavingsAccount::SavingsAccount() : dollars{ 0 }, cents{ 0 }, total_money{ 0.0 } {
}
SavingsAccount::SavingsAccount(unsigned int d, unsigned int c) : dollars{ d }, cents{ c }, total_money{ getDoubleVal(d, c) } {
convert();
}
void SavingsAccount::setValues(unsigned int d, unsigned int c) {
dollars = d;
cents = c;
convert();
}
void SavingsAccount::deposit(unsigned int d, unsigned int c) {
setValues(dollars + d, cents + c);
}
void SavingsAccount::withdraw(unsigned int d, unsigned int c) {
//You should also check for unsigned int underflow here
setValues(dollars - d, cents - c);
}
ostream& SavingsAccount::print(ostream& o) const {
o << total_money;
return o;
}
ostream& operator<<(ostream& o, const SavingsAccount& sa) {
return sa.print(o);
}
int main() {
SavingsAccount sa1 = SavingsAccount();
SavingsAccount sa2 = SavingsAccount(1337, 42);
cout << sa1 << sa2 << endl;
return 0;
}
Sorry for any mistakes in the code, especially formatting, I wrote this on my phone...
In an interview I was asked to create two classes. The first abstract class is called Number, which supports one operation “+”. And the other one fraction which implements the "Number" abstract class.
Further: For a Fraction once added, it needs to be displayed in its original form. That is, 2/4 has to be displayed as “2/4”, not “1/2” or “0.5”.
No Other detail was provided to me.
Below is what I had tried (Incomplete).
My main.cpp
#include <iostream>
#include "Fraction.h"
using namespace std;
int main()
{
Fraction sumFraction;
Fraction n11(1,2);
Fraction n21(1,2);
cout << n11.getValuenum() << "/";
cout << n11.getValueden() << endl;
cout << n21.getValuenum() << "/";
cout << n21.getValueden() << endl;
sumFraction = n11 + n21;
cout << sumFraction.getValuenum() << endl;
cout << sumFraction.getValueden() << endl;
return 0;
}
My Numbers.h // ABSTRACT CLASS
#pragma once
template<class T>
class Number
{
virtual T& operator= (const T &) = 0; // first parameter is implicitly passed
virtual const T operator+ (const T &) = 0;
virtual void display() = 0;
};
My Fraction.cpp
#include "Fraction.h"
int Fraction::getValuenum()
{
return this->a1;
}
int Fraction::getValueden()
{
return this->a2;
}
Fraction::Fraction()
{
a1 = 0;
a2 = 0;
}
Fraction::Fraction(int num, int den)
{
a1 = num;
a2 = den;
}
void Fraction::display()
{
// will display the number in its original form
}
Fraction& Fraction::operator=(const Fraction &num)
{
a1 = num.a1;
a2 = num.a2;
return *this;
}
const Fraction Fraction::operator+(const Fraction &numberTwo)
{
Fraction n1;
n1.a1 = this->a1*numberTwo.a2 + this->a2*numberTwo.a1;
n1.a2 = this->a2*numberTwo.a2;
return n1;
}
My Fraction.h
#pragma once
#include "Number.h"
class Fraction : public Number<Fraction>
{
private:
int a1;
int a2;
public:
void display();
Fraction();
Fraction(int num, int den);
int getValuenum();
int getValueden();
Fraction& operator= (const Fraction &); // first parameter is implicitly passed
const Fraction operator+ (const Fraction &); // first parameter is implicitly passed
};
Below are my question:
Do I really need to pass numerator and denominator separately from my Main function for each fraction. Currently, I am passing it as separately to keep track of numerator and denominator which might be helpful while adding and returning the result in terms for fraction.
With my operator + logic if I add 1/4+1/4 I get 8/16, what is expected is I guess 2/4 which we get if we add normally. So how to add using numerator and denominator and to keep the fraction in such a way, so that if output is 2/4 then 2/4 and not 1/2 or 0.5.
Please help me.
Some remarks:
you should not allow the denominator to be 0 because it gives an inexistent number (infinity or undeterminated)
you should definitely not initialize the denominator to 0 for same reason (1 seems a more reasonable value)
the correct (mathematical) addition of fractions is (*):
a/b + c/d = (ad +bc)/bd
Instead of (or in addition to) the display method, I would advise you to write a ostream& operator << (ostream&, const Fraction&) overload. That would allow you to just write in you main
std::cout << n11 << " + " << n21 << " = " << sumFraction << std::endl;
I did not really understand you first question, but I would add a conversion from an int:
Fraction(int n): a1(n), a2(1) {};
to allow to write directly Fraction(1, 2) + 1 or Fraction(1) + Fraction(1/2) (the first element of the addition must be a Fraction)
(*) this is the simple and general way. You could also use the least common multiple to get cleaner results:
den = lcm(b,d)
a/b + c/d = (a * den/b) + c * den/d) / den
That way you would get 1/4 + 2/4 = 3/4 instead of 12/16
But computing the LCM is far beyond this answer...
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Can someone just explain whats going in this code? You don't have to go line by line but a general summary would be really helpful. It's similar to other fraction class c++ code so you don't have to completely refer to this code.
#include<iostream>
using namespace std;
class Fraction
{
private:
int num, den;
public:
Fraction(int n = 1, int d = 2) : num(n), den(d) { }
void show() { cout«num«”/”«den; }
Fraction operator+(Fraction f) const
{ return Fraction(num+f.num, den+f.den); }
Fraction operator-(Fraction f) const
{ return Fraction(num-f.num, den-f.den); }
Fraction operator*(Fraction f) const
{ return Fraction(num*f.num, den*f.den); }
Fraction operator/(Fraction f) const
{
int rNum = (f.den*num)/den;
return (rNum, f.num);
}
friend ostream& operator«(ostream& out, Fraction& f)
{ cout«f.num«”/”«f.den; return out; }
friend istream& operator»(istream& in, Fraction& f)
{ cout«”\nEnter Numerator: “; cin»f.num; cout«”Enter Denominator: “;
cin»f.den; cout«f.num«”/”«f.den; return in; }
int ndMax()
{ return (num<=den) ? num:den; }
void reduce()
{
for(int i = 2; i<=ndMax(); i++)
if(num%i == 0 && den%i == 0)
{ num = num/i; den = den/i; i = 1; }
}
}; //
int main()
{
Fraction f1(5, 6);
Fraction f2(80, 1001);
cout«f1«” and “«f2«endl;
Fraction f3 = f1/f2;
f3.reduce(); cout«f3;
cout«endl;
return 0;
}
// This declares a dependency on the system module, iostream. Specifically, this code uses the
// system provided objects, cout, and cin, for output and input.
#include <iostream>
// This says if the compiler cannot find a symbol, it should try looking in the namespace, std.
using namespace std;
// This defines a type called, Fraction.
class Fraction {
private:
// This declares two private member variables, num, and den, presumably representing the
// numerator and denominator of a fraction. Each object of type Fraction will have its own
// num and den. Because they are private they cannot be accidentally modified outside the
// definition of Fraction. They are the module's secret.
int num, den;
public:
// This declares a constructor. It uses the default argument notation to actually define
// three constructor syntaxes. Two arguments may be given, one, or zero. Fraction() = 1/2,
// Fraction(x) = x/2, and Fraction(x, y) = x/y. A default denominator of 1 would be more
// normal, especially since this constructor can be used to implicitly convert an int into
// a Fraction.
Fraction(int n = 1, int d = 2) : num(n), den(d) { }
// This function outputs a representation of a Fraction to cout. It repeats the definition
// of operator<< below, which violates the DRY principle so it should probably be written
// as: cout << *this;
void show() {
cout << num << " / " << den; }
// This is an operator overload. It allows you to write, Fraction + Fraction. Note that it
// does not add fractions in the expected way, instead it does a vector addition.
Fraction operator+(Fraction f) const {
return Fraction(num + f.num, den + f.den); }
// Similarly broken.
Fraction operator-(Fraction f) const {
return Fraction(num - f.num, den - f.den); }
// Correct multiplication, although normalizing the fraction is kind of expected.
Fraction operator*(Fraction f) const {
return Fraction(num * f.num, den * f.den); }
// Cannot be bothered to decide if this is correct. Multiplying by the inverse would be the
// more obvious thing to do, like: return *this * Fraction(f.den, f.num);
Fraction operator/(Fraction f) const {
int rNum = (f.den * num) / den;
return Fraction(rNum, f.num); }
// These functions support reading and writing a Fraction using streams. Note that they should
// make use of the out and in parameters, then they would work with all stream types.
friend ostream& operator<<(ostream& out, Fraction& f) {
cout << f.num << " / " << f.den;
return out; }
// The prompts here are poor design.
friend istream& operator>>(istream& in, Fraction& f) {
cout << "\nEnter Numerator: ";
cin >> f.num;
cout << "Enter Denominator: ";
cin >> f.den;
cout << f.num << " / " << f.den;
return in; }
// This function does not do what you would expect based on the name. It returns min(num, den).
// It should be declared const, like operator+ is since it is thread-safe.
int ndMax() {
return (num <= den) ? num : den; }
// This is weird and evil. The intent is to normalize the fraction. Euclid's algorithm would
// be the usual way.
void reduce() {
for (int i = 2; i <= ndMax(); i++)
if (num % i == 0 && den % i == 0) {
num = num / i;
den = den / i;
i = 1; // Evil!!! Do not modify the loop variable in the body of the loop.
} }
// There are a number of other functions, not explicit here, that are implicitly generated
// by the compiler. For example a copy constructor and assignment operator.
};
// This is a simple test driver for the Fraction class.
int main() {
Fraction f1(5, 6);
Fraction f2(80, 1001);
cout << f1 << " and " << f2 << endl;
Fraction f3 = f1 / f2;
f3.reduce();
cout << f3;
cout << endl;
return 0; }
So basically I am trying to do a fraction class. It will take in the fraction from user input and perform an addition. For example, I type in 1 5 and 1 7 , for the addition it will print out 12/35.
Here is my .h class:
#include <string>
#ifndef _FRACTION_H_
#define _FRACTION_H_
using namespace std;
class Fraction
{
public:
Fraction();
Fraction(int n, int d);
int getNumerator() const;
int getDenominator() const;
void display();
string to_string();
Fraction operator+(Fraction &second);
private:
int numerator;
int denominator;
};
And this is my .cpp file:
#include "Fraction.h"
#include <string>
include <iostream>
using namespace std;
Fraction::Fraction(){}
Fraction::Fraction(int n, int d)
{
this->numerator = n;
this->denominator = d;
}
int Fraction::getNumerator() const
{
return numerator;
}
int Fraction::getDenominator() const
{
return denominator;
}
Fraction Fraction::operator+(Fraction &second)
{
int n1 = getNumerator() * second.getDenominator();
int n2 = second.getNumerator() * getDenominator();
int d = getDenominator() * second.getDenominator();
return Fraction(n1+n2, d);
}
string Fraction::to_string()
{
return (getNumerator() + "/" + getDenominator()) ;
}
And this is my main method:
bool get_input(Fraction &fract);
int main()
{
Fraction fraction1, fraction2;
if (((!get_input(fraction1)) || (!get_input(fraction2))))
cout << "Invalid Input!" << endl;
else
{
// Test harness for Arithmetic Operator Overloading
Fraction result = fraction1 + fraction2;
cout << "Addition = " << result.to_string() << endl;
}
bool get_input(Fraction& fract)
{
int num, den;
cout << "Enter numerator & denominator (separated by space)" << endl;
cin >> num >> den;
if (cin.fail())
return false;
Fraction f(num,den);
fract = f;
return true;
}
}
It's managed to take in the user input. But however, it does not print out the result. Thanks in advance.
There maybe other problems, but the Fraction::to_string()
function is clearly wrong: the types in the return expression
are int, char const* and int. The result of adding these
is a char const*, but given that the string literal is only
two characters long, if the sum of the two int is greater than
two, you have undefined behavior. You need to convert the int
to strings first; the simplest way to do this is to use
std::ostringstream:
std::string
Fraction::to_string()
{
std::ostringstream results;
results << numerator << '/' << denominator;
return results.str();
}
Normally, one would expect a compiler error when you misuse
types like this, but for historical reasons: string literals
have type char const[], not std::string; char const[]
converts almost everywhere to char const*; C++ supports
adding integral values to pointers; and std::string has
a constructor which does an implicit conversion from char
const*.
You use "+" operator between literals ("/") and int in your to_string method
The compiler is trying to do some implicit conversion and it ends up with a point (int + int + char*, best guess is a char*), which is then transformed into a std::string using the correct constructor
Change your method to use stringstream (and you'll have finer control on formatting):
string Fraction::to_string()
{
std::stringstream s;
s << getNumerator() << "/" << getDenominator();
return s.str();
}
reference : http://www.cplusplus.com/reference/sstream/stringstream/