Sean
Sean

Reputation: 4515

How to output fraction instead of decimal number?

In C++, When I calculate 2/3, it will output decimal values, how can I just get the original format (i.e.g 2/3) instead of 0.66666667

Thanks

Upvotes: 7

Views: 50564

Answers (13)

vikas bajpai
vikas bajpai

Reputation: 1

Use greatest common divisor concept.

if we divide the numbers with gcd of their numbers we get least possible value of those.example:-

#define si long long
int main() {
si int total=4;
si int count=2;
si int g= __gcd(count,total);
count/=g;
total/=g;
cout<<count<<"/"<<total<<endl;
}
for more reference check out this:-https://www.codechef.com/viewsolution/17873537

Upvotes: 0

Akash
Akash

Reputation: 1

#include <iostream>
using namespace std;

int main() {
    int a,b,q,r;
    cin>>a>>b;//first number and second number
    q = a/b;
    r = a-q*b;
    cout<<q<<" "<<r<<" "<<"/"<<" "<<b<<"\n";
    return 0;
}

I just got quotient by a/b then got the remainder by a-q*b. open for suggetions if any.

Upvotes: 0

osama khalid
osama khalid

Reputation: 1

This is a program to convert a decimal number into a fraction

#include<iostream>
using namespace std;

int main()
{

    float num, origNum, rem = 1;
    int den = 1, i, count=0, gcd=1;

    cout << "Enter any float number to convert it into mixed fraction: ";
    cin >> origNum;

    num = origNum - static_cast<int>(origNum);

    if (num > 0.1)
    {
        while ( (rem > 0.1) )
        {
            num = num * 10;
            rem = num - static_cast<int>(num);
            count++;
        }

        for (i = 1; i <= count; i++) // counter is for the calculation of denominator part of mixed fraction 
        {
            den = den * 10;
        }

        for (i = 2; i <= num|| i<=rem; i++)
        {
            if( (static_cast<int>(num) % i == 0) && (den % i == 0) )
            {
                gcd = i;
            }   
        }

        cout << (static_cast<int>(origNum)) << " and " << (static_cast<int>(num))/gcd << "/" << den/gcd;
    }
    else
        cout << (static_cast<int>(origNum));

    return 0;   
}

Upvotes: -1

Abhishek Jain
Abhishek Jain

Reputation: 493

Dividing both numbers with their HCF might help.

Upvotes: 0

EmPlusPlus
EmPlusPlus

Reputation: 181

I am beginner and this way that I use may not be a proper way

#include <iostream>

using namespace std;
int main ()
{
  double a;
  double b;
  double c;

  cout << "first number: ";
  cin >> a;
  cout << "second number: ";
  cin >> b;

  c = a/b;
  cout << "result is: " << c << endl;

  if (b != 0) {
    if (a > 0) {
      if (c - (int)c > 0 && c - (int)c < 1)
        cout << "fraction: " << a << "/" << b;
    } else {
      if (c - (int)c < 0 && c - (int)c < 1)
        cout << "fraction: " << a << "/" << b;
    }
  }

  return 0;
}

Upvotes: 0

Thomas Matthews
Thomas Matthews

Reputation: 57678

To simplify efforts, I suggest you stick with known denominators if possible.

I'm working with an application where the fractions are restricted to denominators of powers of 2 or using 3 (for thirds).

I convert to these fractions using an approximation (rounding to the nearest 1.0/24.0).

Without some restrictions, finding the denominator can be quite a chore and take up a lot of the execution time.

Upvotes: 2

Aak
Aak

Reputation: 182

write your own Rational class to calculate divisions

class Rational
{
public:
    int numerator, denominator;

    Rational(int num, int den=1){
        numerator = num;
        denominator=den;
    }
    Rational(Rational other){
        numerator = other.numerator;
        denominator = other.denominator;
    }
    double operator / (int divisor){
            denominator *= divisor;
            simplificate();
            return getrealformat();
    }
    Rational& operator / (int divisor){
            denominator *= divisor;
            simplificate();
            return this;
    }
    Rational& operator / (Rational &divisor){
            numerator *= divisor.numerator;
            denominator *= divisor.denominator;
            simplificate();
            return this;
    }
    double operator / (int divisor){
            denominator *= divisor;
            simplificate();
        return getrealformat();
    }
    double getrealformat(){
        return numerator/denominator;
    }
    simplificate(){
        int commondivisor = 1;
        for(int i=2;i<=min(abs(numerator), abs(denominator));i++)
            if( numerator%i == 0 && denominator%i == 0 )
                commondivisor = i;
        numerator /= commondivisor;
        denominator /= commondivisor;
    }
};

use

Rational r1(45), r2(90), r3=r1/r2;
cout<<r3.numerator<<'/'<<r3.denominator;
cout<<r3.getrealformat();

Upvotes: 6

sleske
sleske

Reputation: 83587

If I understand correctly, you have a floating point number (a float or double type variable), and you'd like to output this value as a fraction.

If that is the case, you need to further specify your question:

  • A FP number is a fraction, by definition: A FP number consists of two integers, a mantissa m and an expontent e (and a sign, but that's irrelevant here). So each FP number is really a pair (m,e), and the value f it represents is f=mb^e (where b is a fixed integral base, usually 2). So the natural representation as a fraction is simply m / b^(-e) with e<0 (if e>=0 , f is integral anyway).
  • However, you probably want to get the fraction with the smallest reasonable divisor. This is a different question. To get is, you could e.g. use the bestappr function from the Pari/GP library. In your case, you'd probably use bestappr(x, A), with x your input, and A the largest denominator you want to try. bestappr will give you the fraction closest to x whose denominator is still smaller than A.

Upvotes: 8

Mauro Vanetti
Mauro Vanetti

Reputation: 512

You have to store them in some sort of Fraction class with two integer fields. Of course, you have to simplify the fraction before using it for output.

You can develop your own class or use some libraries, like this one for exact maths: CLN - Class Library for Numbers

Upvotes: 4

ThomasMcLeod
ThomasMcLeod

Reputation: 7769

You can store all your fraction's numerators and denominators as intergers. Integers have exact representations in binary.

Upvotes: 2

Dirk is no longer here
Dirk is no longer here

Reputation: 368201

how can I just get the original format (i.e.g 2/3) instead of 0.66666667

Only with great difficulty by wrapping something like the GMP library with custom output operators. Below is a bit more on GMP:

What is GMP?

GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on. GMP has a rich set of functions, and the functions have a regular interface.

The main target applications for GMP are cryptography applications and research, Internet security applications, algebra systems, computational algebra research, etc.

GMP is carefully designed to be as fast as possible, both for small operands and for huge operands. The speed is achieved by using fullwords as the basic arithmetic type, by using fast algorithms, with highly optimised assembly code for the most common inner loops for a lot of CPUs, and by a general emphasis on speed.

GMP is faster than any other bignum library. The advantage for GMP increases with the operand sizes for many operations, since GMP uses asymptotically faster algorithms.

The first GMP release was made in 1991. It is continually developed and maintained, with a new release about once a year.

Upvotes: 4

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

You can't. You would need to write a class dedicated to holding rational numbers (i.e. fractions). Or maybe just use the Boost Rational Number library.

Upvotes: 10

Eamon Nerbonne
Eamon Nerbonne

Reputation: 48066

This is impossible in general: floating point numbers are not precise and do not retain sufficient information to fully reconstruct a fraction.

You could, however, write a function that heuristically finds an "optimal" approximation, whereby fractions with small numerators and denominators are preferred, as are fractions that have almost the same value as the floating point number.

If you're in full control of the code, Oli's idea is better: don't throw away the information in the first place.

Upvotes: 3

Related Questions