How to turn user input into Mixed Fraction in c++?

Viewed 37

#include <iostream>

using namespace std;

int main()
{
    int int1, int2, fraction;
    int coE;
    cin >> int1;
    cin >> int2;
    
            coE = int1 / int2;
            fraction = int1 % int2;
    
    
            if (fraction > 0) {
                cout << coE << " " << fraction << "/" << int2 << endl;
    
            }
            else if (fraction == 0){
                cout << coE;
            }
            else if (coE == 0){
                cout << fraction << "/" << int2;
            }
            else if (fraction < 0 && int2 < 0){
                fraction = fraction * -1;
                int2 = int2 * -1;
                cout << coE << " " << fraction << "/" << int2 << endl;
            }
            else if (fraction < 0){
                fraction = fraction * -1;
                cout << coE << " " << fraction << "/" << int2 << endl;
                }
            }
    return 0;
}

    }

This outputs fine but has some issues with negative numbers, I tried fixing it but it hasn't really worked out. coE is the Coefficient of the fraction. I need to use if statements to fix. It used to output the code and would work but now it doesn't. It didn't work when both numbers are negative and I tried to fix it, by adding an if statement but nothing happened after that. Is there a simpler way rather than this to use if statements in this case.

0 Answers
Related