Convert given Float value to equivalent Fraction | C ++ program for the above approach ; Function to convert the floating values into fraction ; Initialize variables ; Traverse the floating string ; Check if decimal part exist ; Check if recurrence sequence exist ; Retrieve decimal part and recurrence re sequence ; Traverse the string ; Convert string to integer ; If no recurrence sequence exist ; Initialize numerator & denominator ; No reccuring term ; Print the result ; If reccuring term exist ; Convert reccuring term to integer ; reccu . size ( ) is num of digit in reccur term ; eq 2 - eq 1 ; Print the result ; Driver Code ; Given string str ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findFraction ( string s ) { string be_deci = " " , af_deci = " " , reccu = " " ; bool x = true , y = false , z = false ; for ( int i = 0 ; i < s . size ( ) ; ++ i ) { if ( s [ i ] == ' . ' ) { x = false ; y = true ; continue ; } if ( s [ i ] == ' ( ' ) { z = true ; y = false ; continue ; } if ( x ) be_deci += s [ i ] ; if ( y ) af_deci += s [ i ] ; if ( z ) { for ( ; i < s . size ( ) && s [ i ] != ' ) ' ; ++ i ) reccu += s [ i ] ; break ; } } int num_be_deci = stoi ( be_deci ) ; int num_af_deci = 0 ; if ( af_deci . size ( ) != 0 ) num_af_deci = stoi ( af_deci ) ; int numr = num_be_deci * pow ( 10 , af_deci . size ( ) ) + num_af_deci ; int deno = pow ( 10 , af_deci . size ( ) ) ; if ( reccu . size ( ) == 0 ) { int gd = __gcd ( numr , deno ) ; cout << numr / gd << " ▁ / ▁ " << deno / gd ; } else { int reccu_num = stoi ( reccu ) ; int numr1 = numr * pow ( 10 , reccu . size ( ) ) + reccu_num ; int deno1 = deno * pow ( 10 , reccu . size ( ) ) ; int res_numr = numr1 - numr , res_deno = deno1 - deno ; int gd = __gcd ( res_numr , res_deno ) ; cout << res_numr / gd << " ▁ / ▁ " << res_deno / gd ; } } int main ( ) { string str = "23.98(231 ) " ; findFraction ( str ) ; return 0 ; }