Need a project done?

C++ Programming Developer

Search This Blog

C++ program to turn a decimal into a fraction. Writes the number in numerator/denomenator form.

C++ program to turn a decimal into a fraction

Output: 


I would recommend to visit C++ Program to simplify fractional form before understanding the code of this program.

Code:

#include <iostream>
#include <cmath>

void simplify_fraction(int num, int denom);

using namespace std;

int main()
{
double number;
cout << "Enter Number: ";
cin >> number;

double fractional_part = number - floor(number);

for (double i = 0.1, j = 10;  ; i/=10, j*=10)
{
if ( fractional_part >= i )
{
simplify_fraction(number * j, j);
break;
}
}
return 0;
}


void simplify_fraction(int num, int denom)
{
for (int i = denom; i>=2; i--)
{
if (num % i == 0 && denom % i == 0)
{
num = num/i;
denom = denom/i;
}
}
cout << "Fraction: ";
if (denom == 1)
cout << num;
else
cout << num << "/" << denom;
cout << endl;
}

3 comments:

  1. I'm Sorry for being so late in replying.

    ReplyDelete
  2. excellent example, just what i was looking for. bow.

    godspeed,

    simon
    s love nia

    ReplyDelete

"Don't let anyone ever make you feel like you don't deserve what you want."