Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <sstream>
- using namespace std;
- long gcd(long, long);
- string doFrac(double, double);
- int countDigits(double);
- int main(){
- cout << doFrac(66,20);
- }
- long gcd(long a, long b){
- if (a == 0)
- return b;
- else if (b == 0)
- return a;
- if (a < b)
- return gcd(a, b % a);
- else
- return gcd(b, a % b);
- }
- string doFrac(double num, double denom){
- ostringstream s;
- string re;
- double dec;
- long gcd_;
- dec = num / denom;
- if(countDigits(dec) < 7){
- dec *= 100;
- gcd_ = gcd(dec, 100);
- dec /= gcd_;
- int dec2 = dec;
- double temp = 100 / gcd_;
- s << dec2; s << "/"; s << temp;
- re = s.str();
- return re;
- } else {
- int nDec = 0;
- int nine = 0;
- if(gcd(num, denom) == 1){
- s << num; s << "/"; s << denom;
- re = s.str();
- return re;
- } else {
- dec *= 10;
- nDec = dec;
- nine = 9 /gcd(nDec, 9);
- nDec /= gcd(nDec, 9);
- s << nDec; s << "/"; s << nine;
- re = s.str();
- return re;
- }
- }
- }
- int countDigits(double d){
- ostringstream s1;
- string s2;
- s1 << d;
- s2 = s1.str();
- int num;
- for(int i = 0; i < s2.size(); i++){
- num++;
- }
- return abs(num);
- }
- int countDigits(int d){
- ostringstream s1;
- string s2;
- s1 << d;
- s2 = s1.str();
- int num;
- for(int i = 0; i < s2.size(); i++){
- num++;
- }
- return num;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement