Represent the fraction of two numbers in the string format | C ++ program to calculate fraction of two numbers ; Function to return the required fraction in string format ; If the numerator is zero , answer is 0 ; If any one ( out of numerator and denominator ) is - ve , sign of resultant answer - ve . ; Calculate the absolute part ( before decimal point ) . ; Output string to store the answer ; Append sign ; Append the initial part ; If completely divisible , return answer . ; Initialize Remainder ; Position at which fraction starts repeating if it exists ; If this remainder is already seen , then there exists a repeating fraction . ; Index to insert parentheses ; Calculate quotient , append it to result and calculate next remainder ; If repeating fraction exists , insert parentheses . ; Return result . ; Drivers Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string calculateFraction ( int num , int den ) { if ( num == 0 ) return "0" ; int sign = ( num < 0 ) ^ ( den < 0 ) ? -1 : 1 ; num = abs ( num ) ; den = abs ( den ) ; int initial = num / den ; string res ; if ( sign == -1 ) res += " - " ; res += to_string ( initial ) ; if ( num % den == 0 ) return res ; res += " . " ; int rem = num % den ; map < int , int > mp ; int index ; bool repeating = false ; while ( rem > 0 && ! repeating ) { if ( mp . find ( rem ) != mp . end ( ) ) { index = mp [ rem ] ; repeating = true ; break ; } else mp [ rem ] = res . size ( ) ; rem = rem * 10 ; int temp = rem / den ; res += to_string ( temp ) ; rem = rem % den ; } if ( repeating ) { res += " ) " ; res . insert ( index , " ( " ) ; } return res ; } int main ( ) { int num = 50 , den = 22 ; cout << calculateFraction ( num , den ) << endl ; num = -1 , den = 2 ; cout << calculateFraction ( num , den ) << endl ; return 0 ; }