Help With C++ Fraction Calculator Program Please

Hello, I'm currently writing a program that is supposed to add, subtract, divide, and multiply fractions. I've been tinkering with it all day and I just can't seem to get it to work correctly. Right now I'm getting a floating point exception and I have no idea where to begin to fix it. Sorry if this is an easy problem, I'm new to programming.
This is a sample of how the program should look when it's compiled and ran correctly:
Sample compilation and execution
This is the sample input file I am going to be redirecting from:
3/5 + 1/5
12/10 - 1/3
-42/5*1/2
7/4 / 0/5
11/2 + 6/4
This is the expected output:
3/5 + 1/5 = 20/25
12/10 - 1/3 = 26/30
-42/5 * 1/2 = -42/10 = -4 2/10
7/4 / 0/5 could not be solved because division by zero is not defined
11/2 + 6/4 = 56/8 = 7

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
  #include <iostream>

using namespace std;
int main()
{
  int num1, num2; // numerator                                                                                                                       
  int den1, den2; // denominator                                                                                                                     
  int frac1, frac2; // whole fractions                                                                                                               

  den1 > 0;
  den2 > 0;
  frac1 = num1/den1;
  frac2 = num2/den2;

  cin >> num1 >> den1 >> num2 >> den2;
  if (frac1+frac2)
    cout << num1 << "/" << den1 << " + " << num2 << "/" << den2 << " = " << ((num1*den2)+(den1*num2)) << "/" << (den1*den2) << endl;
  else
    if (frac1-frac2)
      cout << num1 << "/" << den1 << " - " << num2 << "/" << den2 << " = " << ((num1*den2)-(den1*num2)) << "/ " << (den1*den2) << endl;
    else
      if (frac1*frac2)
          cout << num1 << "/" << den1 << " * " << num2 << "/" << den2 << " = " << (num1*num2) << "/ " << (den1*den2) << endl;
        else
          if (frac1/frac2)
            cout << num1 << "/" << den1 << " * " << num2 << "/" << den2 << " = " << (num1*den2) << "/ " << (den1*num2) << endl;
 return 0;
 }
Last edited on
For starter you're using an int with division, which is not good since you're more than likely to receive a float value or double.

1
2
3
	int num1, num2; // numerator
	int den1, den2; // denominator
	float frac1, frac2; // whole fractions 


Here you put den1 > 0; but that doesn't do anything, you're suggesting it as an argument (is den1 greater than 0); and the compiler has no idea what to do with this statement.
 
	den2 = den1 = 0;

Also your cin >> num1 >> den1 >> num2 >> den2; comes after the compiler wants a value stored in those variables. Needs to either be initialized values, or put cin before the use of them.
Topic archived. No new replies allowed.