Q:

Write a C++ program to get the fraction part from two given integers representing the numerator and denominator in string format

0

Write a C++ program to get the fraction part from two given integers representing the numerator and denominator in string format

Sample Input: x = 3
n = 2
Sample Output: 1.5

Sample Output:

Fractional part of 3 and 2 = 1.5

Fractional part of 4 and 7 = 0.(571428)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <iostream>
#include <unordered_map> 
using namespace std;

    string fraction_to_decimal(int numerator_part, int denominator_part) {
        string result;
        if ((numerator_part ^ denominator_part) >> 31 && numerator_part != 0) {
            result = "-";
        }

        auto dvd_part = llabs(numerator_part);
        auto dvs_part = llabs(denominator_part);
        result += to_string(dvd_part / dvs_part);
        dvd_part %= dvs_part;
        if (dvd_part > 0) {
            result += ".";
        }
        
        unordered_map<long long, int> lookup;
        while (dvd_part && !lookup.count(dvd_part)) {
            lookup[dvd_part] = result.length();
            dvd_part *= 10;
            result += to_string(dvd_part / dvs_part);
            dvd_part %= dvs_part;
        }

        if (lookup.count(dvd_part)) {
            result.insert(lookup[dvd_part], "(");
            result.push_back(')');
        }
        return result;
    }


int main(void)
{
    int x = 3;
    int n = 2;
    cout << "\nFractional part of " << x << " and " << n << " = " << fraction_to_decimal(x, n) << endl; 
    x = 4;
    n = 7;
    cout << "\nFractional part of " << x << " and " << n << " = " << fraction_to_decimal(x, n) << endl; 
    return 0;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now