How to output fraction instead of decimal number?

后端 未结 13 1985
余生分开走
余生分开走 2020-12-01 21:59

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

相关标签:
13条回答
  • 2020-12-01 22:20
    #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.

    0 讨论(0)
  • 2020-12-01 22:21

    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

    0 讨论(0)
  • 2020-12-01 22:22

    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.
    0 讨论(0)
  • 2020-12-01 22:23

    Dividing both numbers with their HCF might help.

    0 讨论(0)
  • 2020-12-01 22:26

    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
    
    0 讨论(0)
  • 2020-12-01 22:27

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

    0 讨论(0)
提交回复
热议问题