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
#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.
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
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:
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.Dividing both numbers with their HCF might help.
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
You can store all your fraction's numerators and denominators as intergers. Integers have exact representations in binary.