Fraction addition in C++ - c++

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/

Related

return float when + class

I was trying to take float + objected class and have the result return as float, however, my code just does not work. I am pretty confused. I have added that overload function as a friend to the class. could anyone explain it to me?
With the best regards
#include <iostream>
#include <cstdint>
using namespace std;
#define MAX_NUM_SENSORS 5
enum { INVALID, TEMPERATURE, HUMIDTY };
// The 'Sensors' structure describes a single sensor, it's type and current value.
// type - describes the type of sensor 0 (INVALID), 1 (TEMPERATURE), 2 (HUMIDITY)
// value - the current value of the sensor.
// valid - set to TRUE if the sensor is valid, should default to FALSE until set up.
class Sensors
{
public:
friend ostream& operator <<(ostream&, const Sensors&);
friend float operator+ (float,const Sensors&);
private:
int type;
float value;
bool valid = false;
};
ostream& operator<<(ostream& OutStream, const Sensors& OutComp)
{
OutStream << " Type: " << (OutComp.type == TEMPERATURE ? "Temperature" : "Humidity");
OutStream << " Value: " << OutComp.value << endl;
return OutStream;
}
float operator+ (float adding, const Sensors& added)
{
float sum;
sum = added.value + adding;
return sum;
}
int main()
{
Sensors tested();
float m = 1.2 + tested;
cout << m;
return 1;
}
I ran your code in godbolt
There is some kind of simple fixes.
int main()
{
Sensors tested();
// ^--- remove this parenthesis (or use braces, it's ambigious)
float m = 1.2 + tested;
// ^----- This is a double, change this to "1.2f"
cout << m;
return 1;
}
Decimal values in code is double by default, you need to add the postfix f to specify that it is a float. Or you could add a definition of operator + with double as a parameter.
Here is a compiling version of your code

Add fractions using operator overloading

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...

Adding a fractions and classes - Woot

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.

Fractions class in c++ explaination [closed]

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; }

calculate polynomial with coefficients as abstract class Number

I am struggling with adding operations of classes Natural, Rational, Complex that represent appropriate math objects. I need that to calculate polynomial in x.
All classes inherit abstract class Number. Having all coefficients in an array of Numbers I want to calculate the polynomial. To do so I need operation of multiplying by double (x is double). x gets transformed into Rational and multiplied. This works fine. My problem is how to add classes of abstract type Number?
I can't make it work. All I get is never ending recursion in Number::add(Number) (it invokes itself instead of invoking others methods for types Natural, Rational, Complex).
#include
#include
#include
#include
#include
#include
#include
using namespace std;
class Natural;class Rational;class Complex;
class Number {
public:
virtual string toString() const = 0;
virtual Number *operator*(const Rational) const = 0;
virtual Number *add(const Natural*) const = 0;
virtual Number *add(const Rational*) const = 0;
virtual Number *add(const Complex*) const = 0;
virtual Number *add(const Number *n) const {
n->add(this);
}
};
class Natural : public Number {
friend class Complex;
int n;
public:
Natural(const Natural &s) {
n = s.n;
}
Natural(int number) : n(number) {}
string toString() const {
stringstream ss;
ss << n;
return ss.str();
}
operator Rational() const;
operator Complex() const;
operator int() const {
return n;
}
Number *operator*(const Rational r) const;
Number *add(const Natural* number) const {
return new Natural(n + number->n);
}
Number *add(const Rational*) const;
Number *add(const Complex*) const;
};
class Rational : public Number {
friend class Natural;
int numerator, denominator;
void divideByGCD() {
int a = numerator, b = denominator;
//cout << a << ' ' << b << ' ';
if(a < b) {
int temp = a;
a = b;
b = temp;
}
while (b > 0) {
int r = a % b;
a = b; b = r;
//cout << r << endl;
}
numerator /= a;
denominator /= a;
//cout << a << endl;
}
public:
Rational() {}
Rational(const Rational &s) {
numerator = s.numerator;
denominator = s.denominator;
}
Rational(int n, int d) {
if(d == 0) throw new runtime_error("denominator equals 0");
if(d < 0) {
numerator = -n;
denominator = -d;
} else {
numerator = n;
denominator = d;
}
divideByGCD();
}
Rational(double d) {
int i = 0, mul = 1;
int r = d-floor(d);;
while(r!=0) {
i++; mul *= 10;
r = 10*r-floor(10*r);
}
numerator = (int)mul*d;
denominator = mul;
divideByGCD();
}
string toString() const {
stringstream ss;
ss << numerator;
if(denominator > 1) ss << '/' << denominator;
return ss.str();
}
operator const Complex() const;
operator const double() const {
return (double)numerator/denominator;
}
Number *operator*(const Rational r) const {
return new Rational(numerator*r.numerator, denominator*r.denominator);
}
Number *add(const Rational* r) const {
return new Rational(numerator*r->denominator+r->numerator*denominator, denominator*r->denominator);
}
Number *add(const Natural*) const;
Number *add(const Complex*) const;
};
class Complex : public Number {
friend class Rational;
double real, imaginary;
static const double radius = 10;
public:
Complex() {}
Complex(const Complex &s) {
real = s.real;
imaginary = s.imaginary;
}
Complex(const double r, const double im) : real(r), imaginary(im) {}
string toString() const {
stringstream ss;
ss << real;
if(imaginary != 0) ss << '+' << imaginary << 'i';
return ss.str();
}
Number *operator*(const Rational r) const;
Number *add(const Complex* c) const {
return new Complex(real + c->real, imaginary + c->imaginary);
}
Number *add(const Natural*) const;
Number *add(const Rational*) const;
};
Natural::operator Rational() const {
return Rational(n,1);
}
Natural::operator Complex() const {
return Complex(n, 0);
}
Rational::operator const Complex() const {
return Complex((double)numerator/denominator, 0);
}
Number *Natural::operator*(const Rational r) const {
return new Rational(n*r.numerator, r.denominator);
}
Number *Complex::operator*(const Rational r) const {
return new Complex(real*(double)r, imaginary*(double)r);
}
Number *Natural::add(const Rational *r) const {
if(r->denominator == 1) return new Natural(n+r->numerator);
else return new Rational(n*r->denominator,r->denominator);
}
Number *Natural::add(const Complex *c) const {
return c->add(this);
}
Number *Rational::add(const Natural *n) const {
return n->add(this);
}
Number *Rational::add(const Complex *c) const {
return new Complex(c->real+(double)*this, c->imaginary);
}
Number *Complex::add(const Natural *number) const {
return new Complex(real+number->n, imaginary);
}
Number *Complex::add(const Rational *r) const {
return r->add(this);
}
Number *poly(double x, Number *a[], unsigned int size) {
if(size == 1) return a[0];
else return a[0]->add((*poly(x, a+1, size-1))*Rational(x));
}
int main() {
cout << (Natural(5)*(Rational)2.0)->toString() << endl;
Number *coefs[] = {new Natural(5), new Natural(6)};
cout << poly(2, coefs, 2) << endl;
}
How should I fix Number::add(Number) so that while invoking add on object of type Number program itself figure out which of virtual method add to choose?
This is known as multi-dispatch. Here are some links to look at
Multiple_dispatch
best multimethods implementation
I think the problem is:
virtual Number *add(const Number *n) const {
n->add(this);
}
If you multiply a Rational by a Natural that is stored in a Number *, it can't polymorphicly upcast the Number * to a Natural *. I agree w/g-makulik in that references/values make a lot more sense here, as you are leaking memory all over the place. Remove support for Number + Number. Also, if I add a Natural and a Rational together, I get a Number * back, but what kind of number is it? I think the architecture needs a bit more thought; I might get rid of the base class pure virtual methods entirely (except maybe toString). For example:
class Number
{
public:
virtual string toString() = 0;
};
class Rational : public Number
{
string toString() {...}
// forget 'add', use operators
Rational operator+(const Rational & _rhs) const {Rational ret; ...; return ret;}
Rational & operator+=(const Rational & _rhs) const {...; return *this;}
...
}
Edit
For a quick fix, I think you just need to get rid of virtual Number *operator*(const Rational) const = 0;, and replace it with a version for each sub-class (e.x., Rational * operator*(const Natural) const)
Or, add an enumerated member variable to Number to keep track of the type:
enum Type { NATURAL, RATIONAL, ...}
Type mType;
or use RTTI, such that you can selectively choose the right add method in Number::add:
Number * add(Number * _rhs)
{
if(_rhs->mType == RATIONAL)
return this->add((Rational *)_rhs);
...
}
it looks kinda sloppy, but it will work
it looks like Visitor pattern is what I've been looking for. I wanted to have functions accept and visit in the same class. I believe my mistake was to give them the same name.