So I have a program for a class that Im writing that is all done except for the print function. The input function is correct and the boolean value will update in the input function but when i try to transfer to the print function it always prints (-) and if the user enters 'Y' then it is suppose to bypass the (-) and just print out the fraction. If anyone has anyway to get it to work, I feel like ive tried everything.
Edit: The print function works when i print out just the two fractions in main which are f1 and f2 but the problem is coming when passing the positive into the print function i believe.
class fraction
{
private:
int numerator;
int denom;
bool positive;
public:
void inputFrac();
void printFrac();
fraction fracMult(fraction& b);
fraction fracDiv(fraction& b);
fraction fracAdd(fraction& b);
fraction fracSub(fraction& b);
};
void fraction::printFrac()
{
if (positive=true)
{
cout << "-" << numerator << " / " << denom;
}
else
{
cout << "+" << numerator << " / " << denom;
}
}
void fraction::inputFrac()
{
char tempchar1;
fraction tempchar;
cout<<"Please input the numerator ";
cin>>numerator;
cout<< "Please input the denominator ";
cin>>denom;
cout<<"Is the fraction positive? (Y or N) ";
cin>>tempchar1;
if((tempchar1=='Y'))
{
positive=true;
}
else
{
positive=false;
}
}
You're assigning within your if statement.
Change:
if (positive=true)
to:
if (positive==true)
In your printFrac function, you have if (positive=true). This is incorrect, for what you are doing. You should instead have if (positive) {/*stuff*/}.
Related
I did not get right result for object f3 when I see the f3 using show_fraction() function in
the below code: I am confused. I want to access the sum of f1 and f2 fraction that is stored in f3.But when i see the result in f3 it shows 0/0 in result using fraction_show() function
#include <iostream>
using namespace std;
class fraction
{
private:
float numerator;
float denominator;
char ch;
public:
void get_fraction()
{
cout << "\nEnter the fraction ( in format n/d ): ";
cin >> numerator >> ch >> denominator;
}
void show_fraction()
{
cout << " Fraction is: " << numerator << "/" << denominator;
}
fraction sum(fraction &f, fraction &d) // returns sum of two fractions
{
fraction ff; // to hold the result
// denominator of result
ff.numerator = (f.numerator * d.denominator + f.denominator * d.numerator);
ff.denominator = f.denominator * d.denominator; // numerator of result
return ff;
}
};
int main() // program to test the class
{
fraction f1, f2, f3; // three objects of type fraction created
char ch1;
do
{
f1.get_fraction();
f2.get_fraction();
f3.sum(f1, f2);
cout << "\nSum of ";
f3.show_fraction(); // shows the result ( wrong result)
cout << "\nDo you want to continue ( y/n ): "; // If the user want to continue
cin >> ch1;
} while (ch1 != 'n');
cout << endl;
return 0;
} // end of main
I don't like this style of coding, but at least this works
void sum(fraction &f, fraction &d) // calculates sum of two fractions
{
numerator = (f.numerator * d.denominator + f.denominator * d.numerator);
denominator = f.denominator * d.denominator;
}
then
f3.sum(f1, f2);
I would prefer something like this
friend fraction sum(fraction &f, fraction &d) // returns sum of two fractions
{
fraction ff; // to hold the result
// denominator of result
ff.numerator = (f.numerator * d.denominator + f.denominator * d.numerator);
ff.denominator = f.denominator * d.denominator; // numerator of result
return ff;
}
with this version you need to change the way you call the function
f3 = sum(f1, f2);
I'm not sure which you were intending but you wrote something that was half way between the two versions.
I wrote code to convert decimal fraction number to its binary equivalent. It compiles fine but when executed hangs. The code here prints only first four digits of the binary conversion and if the number if with more than 4 digits, it shows '...' after it. On execution it hangs. Help!
#include <iostream>
using namespace std;
int main()
{
int i, x[10];
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num>=0 && num<=1)
{
i=1;
while (num!=1.000)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
if (i>4)
{
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
cout << "...";
}
else
{
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
}
}
else
{
cout << "The number entered is out of range.";
}
return 0;
}
The first obstacle is the infinite while loop:
Assuming input num=0.5
after first iteration, i=1, x[0]=1, num=0.0
after second iteration, i=2, x[1]=0, num=0.0
Continue forever, i=..., x[i-]1=0, num=0.0
With nothing to break the loop.
while (num!=1.000)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
To fix, consider few changes. There might be other issues.
put a limit on the while loop (i<10 should be a good condition, as this is the size of the x array), or i=4, as this is the maximum output.
The break condition for the while loop should probably be 'num != 0', or even better (num > 1e-7, or other small value).
float has 23 bit in mantissa, maybe it is because you are assign x[i] with i greater than 9.
try this:
//stop when you get four bits
while (i< 5)
Original code has several issues:
1 For input num=.5 and similar (really for all values) cycle never ends (dash-o suggested fix ideas)
2 array x[10] is overflowed with undefined behavior (Edney)
3 nitpicking: 1 is not a “fraction” and better check for a range 0 <= num < 1 instead of 0 <= num <= 1(see also OP printing code; 1 could be added); we could use x[4] with 0<=i <=3
4 string could also be used (PaulMcKenzie). Really “>>” uses string processing for parsing and calculating binary equivalent from which by multiplying by 2 (left shit) and truncation fractional part the code calculates target bits. Both approaches give correct identical results; implementing by string we need to add internal to operator “>>” implementation code to parsing valid formats for floats (decimals) such as 3.14e-1, .2718, 1e-1, etc.
This fix follows OP:
#include <iostream>
using namespace std;
int main()
{
int i, x[5];
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num>=0 && num<1)
{
i=1;
while (i<=4)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
if (num>0)
cout << "...";
}
else
{
cout << "The number entered is out of range.";
}
return 0;
}
This code is without cycles (they are in code implementing “>>”, bitset):
#include <iostream>
#include <bitset>
using namespace std;
int main () {
const int digits = 4;
int fraction;
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num >= 0 && num < 1) {
fraction = num = num * pow (2, digits);
cout << "The binary equivalent is 0.";
cout << bitset<digits> (fraction);
if (num - fraction > 0) cout << "...";
}
else cout << "The number entered is out of range.";
}
I seem to be getting two errors:
A) The first iteration of the loop prints out values fine, however if I press 'y' to go for round 2 it autofills the first number as '0/0'. Shown in the image
B) I want to use the third constructor to set numerator = num and denominator = den However, it just seems to set to default values so I made a temporary fix by commenting out the constructor "Rational(num, den)" and physically wrote out numerator = num; and denominator = den;
Any help is appreciated!
// Add appropriate headers
#include <iostream>
#include <cstdlib>
#include <string>
#include <cmath>
#include <sys/time.h>
using namespace std;
/* KEEP THIS COMMENT
* class Rational
* represents a Rational number. Remember rational means ratio-nal
* which means there is a numerator and denominator having
* integer values. Using good ADT techniques, we have made member
* variable private (also known as instance variables) and made member
* functions public.
*/
class Rational
{
private:
int numerator;
int denominator;
public:
// ToDo: Default Constructor
Rational();
// ToDo: Constructor that takes int numerator
Rational(int i);
// ToDo: Constructor that takes int numerator and int denominator
Rational(int p, int q);
// ToDo: Member function to read a rational in the form: n/d
void input();
// ToDo: Member function to write a rational as n/d
void output();
// ToDo: declare an accessor function to get the numerator
int getNumerator();
// ToDo: declare an accessor function to get the denominator
int getDenominator();
// ToDo: delcare a function called Sum that takes two rational objects
// sets the current object to the sum of the given objects using the
// formula: a/b + c/d = ( a*d + b*c)/(b*d)
void sum(Rational a, Rational b);
// test if two rational numbers are equal.
bool isEqual(const Rational& op);
};
int main()
{
// ToDo: declare three rational objects using the default constructor
Rational a, b, c;
char answer='Y';
// Main loop to read in rationals and compute the sum
do {
cout << "\nEnter op1 (in the format of p/q): ";
a.input();
//Debug line
a.output();
// ToDo: use your input member function to read the first rational
cout << "\nEnter op2 (in the format of p/q): ";
// ToDo: use your input member function to read the second rational
b.input();
//Debug line
b.output();
// ToDo: use the third rational to call Sum with first and second as parameters
c.sum(a, b);
cout << "\nThe sum of op1 and op2 is: ";
c.output();
// ToDo: ouptput the third rational
cout << endl;
cout << "\nTry again (Y/N)?";
cin >> answer;
} while (answer == 'y' || answer == 'Y');
// ToDo: test getters
cout << "\nC's numerator is: " << c.getNumerator() << endl;
cout << "\nC's denominator is: " << c.getDenominator() << endl;
// TODO: Use two constructors to declare a whole number 3/1 and a 4/5
// TODO: Use output to print both rationals
//cout << .output() << " " << .output() << endl;
return 0;
}
// ToDO: Implement your class member functions below.
Rational::Rational()
{
numerator = 0;
denominator = 1;
}
Rational::Rational(int i)
{
numerator = i;
denominator = 1;
}
Rational::Rational(int p, int q)
{
numerator = p;
denominator = q;
}
void Rational::sum(Rational a, Rational b)
{
int num = (a.numerator*b.denominator + a.denominator*b.numerator);
int den = (a.denominator*b.denominator);
numerator = num;
denominator = den;
}
void Rational::input()
{
string in;
int num,den;
//cout << "Enter a rational number in the form of x/y : ";
getline(cin, in);
// find the index position of /
int indx = in.find("/");
// seperator out the numerator
num = atoi(in.substr(0, indx).c_str());
// seperate out the denominator
den = atoi(in.substr(indx+1, in.length()).c_str());
// Rational(num, den);
//cout <<num << " " <<den << endl; // Debug Line
numerator = num;
denominator = den;
//cout <<numerator << " " <<denominator << endl; // Debug Line
}
void Rational::output()
{
cout << numerator << "/" << denominator;
}
// Two getter functions
int Rational::getNumerator()
{
return numerator;
}
Here is the solution. Let me know if you don't know what Buffer is or why do we flush it. I'll try to explain further.
cout << "\nTry again (Y/N)?"; //In main
cin >> answer;
cin.ignore(256,'\n'); // Flush the buffer
Here is the explanation.
Yeah, it(cin) will work fine, As cin doesn't have any issue with buffer. But the issue is with getline. Now let's explain why. First, you need to know how the computer takes input in the program. Whenever you cin some value like cin>>x. The value doesn't directly go into x. Firstly it is stored in some temporary location named buffer. That's why you can press backspace on your console. If it directly writes in more variable(memory), you can't press backspace. It means suppose entering string you wrote "appke", but you want to write "apple " you can press backspace(until you haven't pressed enter). Now, what happens you take input with cin as you give input and press Enter for the next input. Like in your case you pressed "y" and then enter(which is denoted by "\n"). So as enter data it goes into the buffer and then you press enter that enter also goes into buffer but system picks only data from buffer like "y" in your case. So your buffer still has "\n" from previous data. Now come to getline. It has one parameter named "delim" [See-here]http://www.cplusplus.com/reference/string/string/getline/ who tells getline when to stop taking input. By default its values is "\n". Now from your previous entry, your buffer has already "\n" in it. So as getline comes in contact with the buffer, it sees "\n", and it thinks that data for input is present as he finds "\n" in the buffer which is the indicator when to stop. That's why it didn't ask for input. Now come to a solution. If ever you think to use getline after cin. All you need to do is to remove "\n" from the buffer. So all you do is cin.ignore("\n"). You are asking cin to ignore "\n" which was present in the buffer. So when control goes to getline. It ignores the already present "\n" in the buffer and works normally.
Just to start thank you very much for helping me with this program. I am very new to C++ and I could really use some help. This program is designed to take two fractions (for this example lets use 1/2 and 1/4) and add, subtract, multiply, and divide the two fractions. So far I have only gotten to the addition part but I am already confused. The output for the addition is 0/0 and not 3/4. I'm not sure why this is happening and I need some help. Also I am try to use and get used to using structs so if you discover a solution to the problem without using structs please do not submit your answer.
Please help me correct what ever is wrong!
#include <cstdlib>
#include <iostream>
#include <math.h>
/*
Name: Fraction
Author:
Date: 13/10/14 17:33
Description: Takes two fractions and outputs them in different ways
*/
using namespace std;
struct frac {
int A, B, C, D;
};
frac new_frac () ;
frac addition_frac () ;
frac subtraction_frac () ;
frac multiply_frac () ;
frac divide_frac () ;
void printAdd (frac add) ;
int main(int argc, char *argv[])
{
frac fraction;
frac add;
new_frac () ;
addition_frac();
cout << "Addition = " ;
printAdd (add) ;
system("PAUSE");
return EXIT_SUCCESS;
}
// A function that asks the user for a fraction (Ex: 1/2 and 1/4)
frac new_frac () {
frac fraction;
int Aa;
int Ab;
int Ba;
int Bb;
cout << "Enter first numerator " ;
cin >> Aa;
cout << "Enter first denominator " ;
cin >> Ab;
cout << "Enter second numerator " ;
cin >> Ba;
cout << "Enter second denominator " ;
cin >> Bb;
fraction.A = Aa;
fraction.B = Ab;
fraction.C = Ba;
fraction.D = Bb;
cout << "Fraction 1 = " << fraction.A << "/" << fraction.B ;
cout << endl;
cout << "Fraction 2 = " << fraction.C << "/" << fraction.D ;
cout << endl;
return fraction;
}
// A function to add the fractions
frac addition_frac () {
frac add ;
frac fraction ;
add.A = (fraction.A * fraction.B) + (fraction.C * fraction.D) ;
add.B = fraction.A * fraction.D ;
return add;
}
void printAdd (frac add) {
frac fraction;
cout << add.A << "/" << add.B << endl ;
}
First of all you have just declared type ( struct frac ) globally whereas you are defining variables locally ( inside main ). That means you have to pass these variables to another function by reference if you want that function to change your variables ( like in this case you want your function to fill in values into your variable ).
frac fraction;
frac add;
new_frac (frac& fraction, frac& add) ; //assuming frac is typedefed.
addition_frac (frac& fraction, frac& add);
Your new_frac() and addition_frac() functions each have their own local variables. It looks like you were trying to deal with them as if they were global variables.
I would suggest your struct to contain only two numbers (one numerator and one denominator), and then have a function to add them with the signature frac add_frac(frac frac1, frac frac2) and call it from main like so: frac sum = add_frac(first, second), and then call your function for printing a fraction with the result. Your struct should also have a constructor for building a new fraction like so: frac first(1, 2).
Hope this helps.
I cannot for the life of me fathom why I'm getting infinite values returned when I input a normal fraction into the code. Everything but the GCD (Greatest common divisor) seems to be working.
Is there a blatantly obvious logic error somewhere within this?
I've done my research and found various answers to the question, I mean Wikipedia even GIVES YOU code to do it, but I'd like to figure out how to make it work the way I've coded it the way it is now.
#include <iostream>
#include <stdlib.h>
#include <cmath>
#include <math.h>
using namespace std;
class Fraction
{
private:
double num;
double den;
double fraction;
double temp;
public:
void setNum();
void setDen();
int getNum();
int getDen();
void lcdOutput();
void decOutput();
int gcd();
};
void Fraction::setNum(){
cout << "Enter a value for your numerator: " << endl;
cin >> num;
}
void Fraction::setDen(){
cout << "Enter a value for your denominator: " << endl;
cin >> den;
}
int Fraction::getNum(){
return num;
}
int Fraction::getDen(){
return den;
}
int Fraction::gcd(){
Fraction set;
if(num > den){
if(fmod(num, den) == 0){
den = temp;
return temp;
}
else{
den = fmod(num, den);
set.gcd();
}
}
else{
if(fmod(den, num) == 0){
num = temp;
return temp;
}
else{
num = fmod(den, num);
set.gcd();
}
}
}
void Fraction::lcdOutput(){
Fraction set;
set.gcd();
num = num / temp;
den = den / temp;
cout << "Fraction in lowest terms: " << num << "/" << den << endl;
}
void Fraction::decOutput(){
double decimal = num / den;
cout.precision(4);
cout << "The fraction in decimal form is: " << decimal << endl;
}
int main(){
Fraction set;
set.setNum();
set.setDen();
set.getNum();
set.getDen();
set.lcdOutput();
set.decOutput();
return 0;
}
Here's what I can determine just by stepping through your code.
Starting at main, you instantiate an instance of type Fraction named set. You assign its numerator and denominator via calls to set.setNum() and set.setDen(). The calls to getNum() and getDen() do nothing in this case, as they are not being assigned to anything.
Then you call lcdOutput(), so let us begin stepping through that.
You begin by instantiating a LOCAL instance of Fraction (not sure why you want to do this, it appears to me that this may be a conceptual mistake), and then call set.gcd() for that local instance. Calling set.gcd() will call the method for THAT INSTANCE, and it seems to me that what you really want is this->gcd() or simply gcd().
You follow up by setting num = num / temp and den = den / temp, but temp is still uninitialized at this point. If the variable is left uninitialized, it can (and usually is) pointing to garbage. This probably explains why you are getting nonsensical values returned.
I went back and figured it out on my own. I saw some of the comments and noticed my very large conceptual and logical errors. Here's to anyone that has the same question!
int gcd(double num, double den){
if(den == 0){
return num;
}
return gcd(den, fmod(num, den));
}
void Fraction::lcdOutput(){
double temp = gcd(num, den);
cout << "Fraction in lowest terms: " << num / temp << "/" << den / temp << endl;
}