C++ Exercises: Get the fraction part from two given integers representing the numerator and denominator in string format
C++ Math: Exercise-6 with Solution
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 Solution:
C++ Code :
#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;
}
Sample Output:
Fractional part of 3 and 2 = 1.5 Fractional part of 4 and 7 = 0.(571428)
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to calculate x raised to the power n (xn).
Next: Write a C++ program to get the Excel column title that corresponds to a given column number (integer value).
What is the difficulty level of this exercise?