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...
Related
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
I'm making a program to overload unary -, +, -, *, /, <<, operators. Everytime I run it, I keep getting this error:
make -s
driver.cpp:63:18: error: invalid argument type 'Complexno' to unary expression
n3 = -n1;
^~~
1 error generated.
make: *** [Makefile:17: driver.o] Error 1
exit status 2
my .hfile
#ifndef COMPLEXNUM_H
#define COMPLEXNUM_H
#include <iostream>
#include <cmath>
using namespace std;
class Complexno {
public :
Complexno(); // Default constructor
Complexno(double r); // Second constructor - creates a complex number of equal value to a real.
Complexno(double r, double c); // (1) Standard constructor - sets both of the real and complex
friend Complexno operator + (Complexno,Complexno);
friend Complexno operator * (Complexno,Complexno);
friend Complexno operator - (Complexno,Complexno);
friend Complexno operator / (Complexno,Complexno);
friend ostream& operator<<(ostream &,Complexno &);
double magnitude(); // (4) Computes and returns the magnitude of a complex number.
void shownum(); // (5) Prints out a complex number in a readable format.
Complexno negate(); // Negates a complex number.
void enternum(); // Reads in a complex number from the user.
private :
double real; // Stores real component of complex number
double complex; // Stores complex component of complex number
};
// Displays the answer to a complex number operation.
void display(Complexno, Complexno, Complexno, char);
#endif
my.cpp file
#include <cmath>
#include "complexnum.h"
// Default constructor sets both components to 0.
Complexno::Complexno() {
real = 0.0;
complex = 0.0;
}
// Second constructor - creates a complex number of equal value to a real.
Complexno::Complexno(double r) {
real = r;
complex = 0.0;
}
// (1) --------------------------------- standard constructor ------------------
//Define standard constructor - sets both of the real and complex components based
Complexno::Complexno(double r, double c) {
real = r;
complex = c;
}
//................overloaded operator + ................
// Adds two complex numbers and returns the answer.
Complexno operator + (Complexno num1,Complexno num2) {
Complexno answer;
answer.real = num1.real + num2.real;
answer.complex = num1.complex + num2.complex;
return answer;
}
// (2) --------------------------------- overloaded operator - ------------------
// Define sub to subtracts two complex numbers and returns the answer.
Complexno operator - (Complexno num1,Complexno num2) {
Complexno answer;
answer.real = num1.real - num2.real;
answer.complex = num1.complex - num2.complex;
return answer;
}
// (3) --------------------------------- overloaded operator * ------------------
// Multiplies two complex numbers and returns this answer.
Complexno operator * (Complexno num1,Complexno num2) {
Complexno answer;
answer.real = num1.real * num2.real - num1.complex * num2.complex;
answer.complex = num1.real * num2.complex + num1.complex * num2.real;
return answer;
}
// --------------------------------- overloaded operator /------------------
// Division two complex numbers and returns this answer.
Complexno operator / (Complexno num1,Complexno num2) {
Complexno answer;
answer.real = (num1.real * num2.real + num1.complex * num2.complex)/(num2.real * num2.real + num2.complex * num2.complex);
answer.complex = (num1.real * num2.real - num1.complex * num2.complex)/(num2.real * num2.real + num2.complex * num2.complex);
return answer;
}
// --------------------------------- overloaded operator << ------------------
ostream& operator<<(ostream &out,Complexno &C)
{
out<<"(";
out<<C.real;
out<<"+";
out<<C.complex<<"i)";
return out;
}
// Negates a complex number.
Complexno Complexno::negate() {
Complexno answer;
answer.real = -real;
answer.complex = -complex;
return answer;
}
// (4) --------------------------------- Magnitude ------------------
// Computes and returns the magnitude of a complex number.
double Complexno::magnitude() {
double answer;
answer = sqrt(real * real + complex * complex);
return answer;
}
// (5) --------------------------------- Print ------------------
// Prints out a complex number in a readable format.
void Complexno::shownum() {
if(complex == 0)
{
cout << "(" << real << ")";
}
else{
if(complex > 0)
cout << "(" << real << "+" << complex << "i" << ")";
else
cout << "(" << real << complex << "i" << ")";
}
}
// Reads in a complex number from the user.
void Complexno::enternum() {
cout << "Enter the real part of the complex number : ";
cin >> real;
cout << "Enter the imaginary part of the complex number : ";
cin >> complex;
}
// Displays the answer to a complex number operation.
void display(Complexno n1, Complexno n2, Complexno n3, char op) {
n1.shownum();
cout << " " << op << " ";
n2.shownum();
cout << " = ";
n3.shownum();
cout << endl;
}
With unary meaning, it only takes one parameter, your overloaded '-' operator is truly not unary, therefore n3 = -n1 is not possible. For something like that you could declare a friend function friend Complexno operator-(const Complexno &z)
and implement it like this:
return Complexno(-z.real,-z.complex);
or a const method inside the class
Complexno operator-() const{return Complexno(-real,-complex);}
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.
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/