C++ Fraction Calculator using Classes and Functions - c++

I am new to StackOverflow, and starting at a new school. I was hoping for some guidance on an assignment. The assignment is to calculate an expression involving two fractions, and output the result. I've been working on this program for days with the knowledge from my textbook, but I guess I am still confused on how to implement functions within a class. I know what I want to do with my values, but I am confused on where to assign them. I tried to read in my values, but when outputting, I get garbage. Any help would be greatly appreciated.
#include <iostream>
using namespace std;
class fraction // Fraction class definition
{
int num,
den;
public:
fraction() // default constructor
{
num = 0;
den = 1;
}
void add(fraction f1, fraction f2) // addition fcn
{
num = (f1.num*f2.den) + (f2.num*f1.den);
den = f1.den*f2.den;
}
void subtract(fraction f1, fraction f2) // subtraction fcn
{
num = (f1.num*f2.den) - (f2.num*f1.den);
den = f1.den*f2.den;
}
void multiply(fraction f1, fraction f2) // multiplying fcn
{
num = f1.num*f2.num;
den = f1.den*f2.den;
}
void divide(fraction f1, fraction f2) // dividing fcn
{
num = f1.num*f2.den;
den = f1.den*f2.num;
}
void output()
{
cout << num << "/" << den << endl;
}
}; // end Fraction class
int main()
{ // begin main
fraction result;
fraction n;
fraction d;
int n1, n2, d1, d2 = 0;
char op;
cout << "Please enter an expression containing two fractions:" << endl;
cin >> n1 >> d1 >> op >> n2 >> d2;
switch (op)
{ // begin switch
case '+':
result.add(n, d);
result.output();
break;
case '-':
result.subtract(n, d);
result.output();
break;
case '*':
result.multiply(n, d);
result.output();
break;
case'/':
result.divide(n, d);
result.output();
break;
} // end switch
//fraction f1(n1, d1);
//fraction f2(n2, d2);
} // end main

The actual answer was given in the very first comment of John3136. Hence, I struggled a bit but finally realized that you probably didn't recognize. So, I will elaborate this a bit:
In main(), you do this:
int n1, n2, d1, d2 = 0;
char op;
cout << "Please enter an expression containing two fractions:" << endl;
cin >> n1 >> d1 >> op >> n2 >> d2;
Stepping through with a debugger, you will realize that this part of program works as expected. After input of e.g.
1 2 + 3 4
the variables will show the following values:
n1: 1
d1: 2
n2: 3
d2: 4
op: '+'
Live demo on ideone
Stepping further, the program pointer will move to
result.add(n, d);
Hmm. You want to add n and d but the debugger says:
n: { num: 0, den: 1 }
d: { num: 0, den: 1 }
The values of n.num, n.den, d.num, and d.den are there as you provided a default constructor for class fraction which effects precisely this.
So, how do you think will n1 be moved to n.num, d1 to n.den, and so on?
What's really missing is a constructor for class fraction to load members num and den (in this case of n and d) with the specified values.
You could introduce a second constructor. In this case, you can modify (and extend) your existing, also:
class fraction {
private:
int num, den; // numerator, denominator
public:
explicit fraction(int num = 0, int den = 1): num(num), den(den) { }
};
Looks confusing? I will explain:
I gave the constructor arguments, but the arguments got default values.
Hence, it still can be used as default constructor. Doing fraction a; will construct fraction 0/1 as before. But, now, you can also do fraction b(3, 2); to construct fraction 3/2. You can even do fraction d(3);. This will construct fraction 3/1 which sounds reasonable to me.
I named the arguments equal to the members. Looks funny and, may be, a bit confusing but it seems to be very usual nowadays. (Actually, I learned this in SO a short time ago.) However, the compiler will understand this correctly (even if it is the one of MS).
I prefixed the constructor with explicit. This prevents that the constructor might be used for implicit conversion. Without explicit, the following would work as well: fraction c; c = 1; i.e. assignment of class fraction from an int. This is a question of design whether or not you want to support this. Implicit conversion can be quite convenient but the compiler might apply it where you don't expect it. I personally got used to make nearly every constructor explicit as I don't like to "lose control" of what the compiler is doing.
Modifying the above constructor as recommended you then can use your class, e.g.:
fraction a(3, 2), b(1, 2);
fraction result; result.add(a, b);
result.output();
Now, it should print the sum of fractions a and b.
A last note:
I consider O'Neil's hint with the operator overloading basically reasonable. You will find answers with code samples in SO. (Some of them, written by me.) ;-) On the other hand, operator overloading is just another handicap. I wouldn't bother too much about this. (May be, in a second version...)
Finally, I made an MCVE to demonstrate the above mentioned with sample code:
#include <iostream>
using namespace std;
class fraction {
private:
int num, den; // numerator, denominator
public:
explicit fraction(int num = 0, int den = 1): num(num), den(den) { }
void add(fraction f1, fraction f2) // addition fcn
{
num = (f1.num * f2.den) + (f2.num * f1.den);
den = f1.den * f2.den;
}
void output() { cout << num << "/" << den << endl; }
};
int main()
{
fraction a0;
cout << "fraction a0: "; a0.output();
fraction a(3, 2), b(1);
cout << "fraction a(3, 2): "; a.output();
cout << "fraction b(1): "; b.output();
fraction c; c.add(a, b);
cout << "fraction c = a + b: "; c.output();
// assignment (using default assignment operator)
fraction d; d = c;
cout << "faction d = c; d: "; d.output();
#if 0 // disabled code
// This will work only if constructor is not explicit:
fraction e = 1; e = 1;
cout << "fraction e; e = 1; e: "; e.output();
#endif // 0
// fraction from input
int n1, n2;
cout << "Input n1 n2: "; cin >> n1 >> n2;
fraction in(n1, n2);
cout << "fraction in(n1, n2): "; in.output();
// done
return 0;
}
Input:
123 321
Output:
fraction a0: 0/1
fraction a(3, 2): 3/2
fraction b(1): 1/1
fraction c = a + b: 5/2
faction d = c; d: 5/2
Input n1 n2: fraction in(n1, n2): 123/321
Live demo on ideone.
After having read your comment, I'm in doubt whether you already understood the concept of class and member function. I'll try my best:
Are you aware that your function add() is a member function? It is as you defined the function inside your class fraction. That means, add() cannot be called without an object (i.e. an instance of fraction).
If you write this into your main() function you get a compiler error:
fraction a, b;
fraction::add(a, b);
Live demo on ideone
The object is another argument that a call of a (non-static) member function (like fraction::add()) urgently needs. May be, you didn't recognize the thing in front of the dot as function argument but it is.
fraction c; c.add(a, b);
/* ^ ^ ^
* | | +--- 2nd argument
* | +------ 1st argument
* +------------ object (which becomes THE this POINTER inside fraction::add())
*/
Hence, fraction.add() has actually three arguments. So, how may the object be accessed? For this, C++ provides a special keyword this. this is a pointer to class, and it provides a pointer to the object for which the member function has been called. Using this, you can access all (other) members of this class – member variables as well as member functions.
(Decades ago, when I tried to understand by myself how C++ and OOP are working, I had a look into the compiled assembly code. I was really surprised to realize that the object before the dot was exactly handled like the other arguments in the parentheses. This was one of my personal Heureka!-moments.)
Access to members (of the same class) can be done inside a member function with this-> but it can be left out as well as the compiler will add this silently if applicable.
Your member function fraction::add() is actually a demonstration of this.
It gets two arguments f1 and f2, processes their members (f1.num, f1.den, f2.num, and f2.den) to perform the addition of fractions, and stores the resp. results in member variables num and den. In this case, num is the same as this->num and den the same as this->den. So, where is this pointing to? This depends on the object for which the member function has been called. For e.g.:
result.add(n, d);
inside of fraction::add(), this will point to result.

Related

How do I create a fraction class with two friend functions in c++

I have an assignment that requires alot of use with classes, the idea of the code is to manipulate fractions to find greatest common denominator (GCD) and other things.
What I need (I know this is long):
Create a Fraction class with 2 private member variables numerator and denominator....one constructor with 2 integer parameters num and den with default values 0 and 1......one display function that prints out a fraction in the format numerator/denominator in the proper form such as 2/3 or 1/2. (2/4 for example should be displayed as 1/2)
HINTS FROM PROFESSOR:
Add a public membeer function called void proper().... that sets numerator and denomonator to the proper form by dividing both by the GCD(greatest common denominator) of them (example... you declare 12/18... after calling proper()...it becomes 2/3 (as the GCD of these is 6)
use public member function GCD() to get the greatest common denominator of the numerator and demoniator...(example 2/4... GCD() returns 2....for 12/18...GCD() returns 6).
[b]Code provided for GCD()
int GCD()
{
int gcd = 0;
int r=0;
u = numerator;
v = denominator;
while (true) {
if (v==0){
gcd = u;
break;
}
else {
r = u%v;
u =v;
v=r;
}
}
return gcd;
}
THEN
Create 2 functions as FRIEND functions of class fraction.
The first one called "sum" takes 2 fraction objects as parameters, it returns a fraction object with the result of the sum of the 2 fraction objects.(example... suppose a=1/4...b=1/2... the result of sum(a,b) should be 3/4.
The second one called "compare"...takes 2 fraction objects as parameters.... it returns 1 if the 2 are equal... and 0 if not. (example....a=1/2...b=2/4.. the result of compare(a,b) is 1)
Write main function to declare fraction objects and demonstrate a working code.
[/b]
So thats what im looking at... here is what I have so far... I know its not very much...
#include <iostream>
using namespace std;
class fraction
{
void friend sum();
void friend compare ();
private:
int numerator;
int denominator;
public:
fraction(int num = 0, int den = 1);
int GCD();
void proper();
void fraction::proper()
{
}
int GCD()
{
int gcd = 0;
int r=0;
u = numerator;
v = denominator;
while (true) {
if (v==0){
gcd = u;
}
else {
r = u%v;
u =v;
}
}
return gcd;
}
void sum()
{
}
void compare()
{
}
void main()
{
}
I am VERY confused about how to set this up with a "1/2" type input... im use to simple inputs like 1 or 2. If someone could help fill in the gaps a bit I would appreciate it... (keep in mind Im a beginner..)... this is my first time working with anything like this and I am in way over my head
Thank you!

How to do a pow function inside of while? C++

Here is the problem I must do(Just for context): Write a program that will input 2 integers from the user, will then calculate the first to the power of the second and then output the result. The Input, calculation and output should be in three separate subprograms/functions. You must calculate the exponentiation using a WHILE loop and multiplying the first number, the required number of times. For this homework only, you are allowed to use global variables to move information between functions.
Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
double a, b, ans;
int main()
{
cout << "Please enter two whole numbers: ";
cin >> a >> b;
cout << conclusion() << calc();
system("pause");
return 0;
}
int calc()
{
double ans = pow(a, b);
return 0;
}
int conclusion()
{
cout << a << " To the power of " << b
<< " is " << ans;
return 0;
}
So here's what I'm having an issue with, I do online classes. The dude is like, "here's a problem, figure it out and just do it." Which is fine I guess, but when things like this come up its hard to find certain tutorials and questions. Anyway, I got my BASE code down. Now I need a while loop, and have no idea what this means: calculate the exponentiation using a WHILE loop and multiplying the first number, the required number of times.
I figured I could just do a while and do
double ans = pow(a, b);
But that's not the case apparently. That's what my chapter taught me, but not with a while and all this extra stuff you need to do for this. I asked a classmate, she said she had a really difficult time as well, and her example to me was:
int a = 0;
int b = 0;
int c = 1;
cin >> a;
cin >> b;
int powerOp(int a, int b, int c)
{
while (b > 0)
{
c = c * a;
b--;
}
cout << c;
return c;
}
I have been working almost all day and can't figure this out. I don't understand why we need to factorize and set the int = 1. I thought it could simply be
double ans = pow(a, b); //a and b being the 2 numbers the user inputs
Its pretty simple, lets say you have 2^3. You and I both agree that it is the same as doing 2x2x2. You mutiplied you first number A by itself B (your second number) times. Now for your loop, what you want have your second number server as your counter AND loop exit condition. Something like this
double YourPowerFunction(int a, int b)
{
int counter = 0;
double result = 1;
while (counter < b)
{
counter++:
result = result * a;
}
return result;
}
Okay so I'm pretty sure I found the answer. Result is the variable for ans
int calc() //function for calculation
{
//Still not sure how I did this one, after hours of playing around with it
while (b > 0) //This code is adding a 0 in the result. I can't figure it out
{
result = result * a;
b--;
}
return (result);
}
This is just a simple solution, as it wants to add a 0 in the end result.

Calculate power with a recursive function on C++

I need to make a program that calculates the power of a given number using a recursive function. I wrote this I can't get it to work, once I get to the function itself it breaks. Any help? Thanks.
#include"stdafx.h"
#include<stdio.h>
#include<iostream>
using namespace std;
float power(float a, unsigned int b);
int main()
{
float a = 0;
unsigned int b = 0;
cout << "Insert base - ";
cin >> a;
cout << "Insert index - ";
cin >> b;
float result;
result = power(a, b);
cout << result;
return 0;
}
float power(float a, unsigned int b)
{
if (b <= 0)
{
return a;
}
return (a*power(a, b--));
}
Instead of b-- you need b-1 (or --b)
b-- reduces b by one, which has no effect because that instance of b is never used again. It passes the unreduced copy of b recursively.
Also, when b is zero, the result should be 1 rather than a
if ( b <= 0) return 1;
return a * power(a, --b);
But this question was asked so many times....
Recursion function to find power of number
Whenever we think about recursion, the first thing that comes to mind should be what the stopping criterion is. Next thing to consider is that we cannot have recursion without the use of a stack. Having said this, let us see at how we are able to implement this power function.
Stopping criteria
X ^ 0 = 1
Unwinding the stack
The base number may be raised to a positive or negative real number. Let us restrict our problem to just integers.
If A is the base and B the power, as a first step, take the absolute
value of B.
Secondly, store A in the stack and decrement B. Repeat
until B = 0 (stopping criterion). Store the result in the stack.
Thirdly, multiply all the A's stored by unwinding the stack.
Now the code
float power(float a, int b)
{
int bx = -b ? b < 0 : b;
if (bx == 0)
{
a = 1;
return a;
}
return 1/(a*power(a, --bx)) ? b < 0 : (a*power(a, --bx));
}

How to implement greatest common divisor to simplify fractions

#include <iostream>
using namespace std;
int g_c_d(int n, int d);
class Fraction
{
private:
//variables to store numerator and denominator
int num;
int denom;
public:
Fraction(){}
Fraction(int num): num(num) {}
Fraction(int num, int denom): num(num), denom(denom) {}
void set_num(int n){ num = n;}
void set_denom(int d){ denom = d;}
int get_numerator() const {return num;}
int get_denominator() const {return denom;}
};
int g_c_d(int n, int d){
return d == 0? n : g_c_d(d, n % d);
}
istream &operator>> (istream &input, Fraction &f)
{
int n, d;
char slash;
input >> n;
input >> slash;
input >> d;
if (d == 0) {n = 0;} //if denom is 0; fraction = 0/0
f = Fraction(n, d);
return input;
}
ostream &operator<<(ostream &output, const Fraction &frac)
{
return output << frac.get_numerator() << "/" << frac.get_denominator();
}
int main()
{
int n, d;
Fraction frac;
int gcd;
n = frac.get_numerator();
d = frac.get_denominator();
gcd = g_c_d(frac.get_numerator() , frac.get_denominator());
cout << "Enter a fraction" << endl;
cin >> frac;
frac.set_num(n/gcd);
frac.set_denom(d/gcd);
cout << "your fraction is: ";
cout << frac << endl;
return 0;
}
Hi im trying to simplify fractions entered by a user. However everytime I enter a fraction that is to be simplified the output returned is "1/0".
Can some one please help, it'll be massively appreciated!
The problem is that you do all your computations on frac before asking the user to input a fraction — and then you overwrite whatever the user inputs. You need to move this bit:
cout << "Enter a fraction" << endl;
cin >> frac;
much, much higher up.
When you are setting up the code you have:
Fraction frac;
This calls the default constructor for Fraction. Because you never initialized the members in the constructor you get the default initizliation for the int type which is 0. Then:
n = frac.get_numerator();
d = frac.get_denominator();
This makes n and d 0. From that point onwards you are using those values of n and d. These values however are not the values from the user inputted frac but are just the values you get from the defaults. Change your code to read in the user inputted value for frac before you do any calculations.
The main lesson to learn here is to make sure you don't use uninitialized variables. Generally speaking when you compile with all warnings enabled this is the sort of thing that compilers will warn about.
You may be diving by zero because the default constructor doesn't assign value to the denominator. In the case where the denominator is set to zero, the gcd() function will divide by zero, on the first time in main.

C++ overloading + operator not working

Hello guys look to my code I'm trying to make a program which asks you to enter the first value by grams And the second value is kilograms and then convert kilograms to grams by an overloaded + operator but it doesn't work why
#include <iostream>
using namespace std;
class ADD{
private:
int Fval;
int Sval;
public:
ADD(){
cout << "WELCOME TO OUR PROGRAM"<<endl<<"PLEASE ENTER THE FIRST VALUE BY GRAMS :";
cin >> Fval;
cout << "PLEASE ENTER THE SECOND VALUE BY KILOGRAMS :"; cin >> Sval;
}
ADD operator+(ADD& add){
add.Sval *= 1000;
return add;
}
int plus(){
return Fval+Sval;
}
};
int main(){
ADD a1;
cout << "THE TOTAL VALUE = " << a1.plus() << " GRAMS";
}
No Effect look to the output
WELCOME TO OUR PROGRAM
PLEASE ENTER THE FIRST VALUE BY GRAMS :2
PLEASE ENTER THE SECOND VALUE BY KILOGRAMS :3
THE TOTAL VALUE = 5 GRAMS
That means the + operator doesn't multiply 3 by 1000
Why??
That's because you're not calling operator +.
You're calling ADD::plus():
int plus(){
return Fval+Sval;
}
Fval and Sval are integers, which you're adding up. It's as simple as that.
EDIT:
Your code is fishy.
ADD operator+(ADD& add){
add.Sval *= 1000;
return add;
}
Multiplication inside operator +? Really? Also, not that you're modifying the parameter, which you shouldn't. It's not intuitive. If you really must do this:
ADD operator+(const ADD& add){
ADD ret;
ret.Sval = add.Sval * 1000;
return ret;
}
The way operator overloading works is that if you have an object of type X, like so:
class X {
public:
X( int v ) : x( v ) {}
int value();
X operator +( const X& y ) {
return X( value() + y.value() );
}
private:
int y;
};
Now if you declare two objects of type X, say X ex and X wye, you can say
X zed = ex + wye;
and get the right result. If type X had more than just a single int field the effect would be more interesting. For example, you could implement 2D vectors and points, and then operations that add and subtract vectors, to get vectors, add and subtract vectors to/from points to get points, and subtract points to get vectors.
Hopefully this will give you enough of an idea of what's going on to be able to restructure your code to get it to do what you want. I may have a detail of syntax wrong, as I'm typing as I go.
Also, I often find the right thing is to declare a friend operator when I want a binary operator:
friend operator + ( vector2D a, vector2D b );
...
inline operator + ( vector2D a, vector 2D b ) {
return vector2D ( a.x + b.x, a.y + b.y );
}