This program should take two inputs (numerator and denominator)
and rewrite the function in simplified form, if numerator>denominator,
it should be rewritten in mixed form, and if the denominator is negative, the - sign should be moved above.
I have a few issues with this program:
Fractions that should not return a mixed number (ex. 4/2), return it anyway (4/2= 2 0/2) instead of just 4/2=2.
in line 26 (divide by zero), I would like to raise an error, but I am not sure if I am doing it right, since anytime I input 0 as the denominator, the whole program blocks.
everytime I obtain the outcome, the program should ask (try again y/n ?) right away, but it doesn't.
Instead I have to type something new and then it exits the command prompt.
I have no idea what is the issue here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
#include "pch.h"
#include <iostream>
#include<algorithm>
#include<exception>
using namespace std;
int gcd_numdem(int a, int b)
{
int i, gcd;
a = abs(a);
b = abs(b);
for (i = 1; i <= a && i <= b; i++)
{
if (a%i == 0 && b%i == 0)
{
gcd = i;
}
else if (a == 0)
{
gcd = 0;
}
else if (b == 0)
{
throw invalid_argument( "ERROR: cannot divide by zero" );
}
}
return gcd;
}
void num_den(int num, int den)
{
if ((abs(num) > den) && (den>0) && (gcd_numdem(num,den)!=0))
{
cout << (num / gcd_numdem(num, den)) / (den / gcd_numdem(num, den)) << " "
<< (num / gcd_numdem(num, den)) % (den / gcd_numdem(num, den)) << "/" <<
abs(den) / gcd_numdem(num, den) << endl;
}
else if ((abs(num) > den)&&(den < 0) && (gcd_numdem(num, den) != 0))
{
cout <<"-"<<( num / gcd_numdem(num, den)) / (den / gcd_numdem(num, den)) << " "
<< (num / gcd_numdem(num, den)) % (den / gcd_numdem(num, den)) << "/" <<
abs(den) / gcd_numdem(num, den) << endl;
}
else
{
cout << num / gcd_numdem(num, den) << "/" << den / gcd_numdem(num, den) << endl;
}
}
int main()
{
char answer;
do {
int x, y;
cout << "enter numerator" << endl;
cin >> x;
cout << "enter denominator" << endl;
cin >> y;
num_den(x, y);
cin >> answer;
cout << "try again(Y/N)?" << endl;
} while (answer == 'Y' || answer == 'y');
return 0;
}
|