题目来自编程之美
题目:
举例:
0.3333(3333) = 1/3
0.285714(285714) = 2/7
0.3(000) = 3/10
0.25 = 1/4
思路:
代码:
注意:假设输入的参数形式为0.XXXX的形式,且均为正数。
#include <iostream>
#include <string>
#include <assert.h>
#include <math.h>
using namespace std;
long long Gcd(long long x,long long y)
{
if (y > x)
{
return Gcd(y,x);/*要求x > y*/
}
return y == 0 ? x : Gcd(y, x - y);
}
void RepresentExactly(string strNum)
{
assert(strNum != "");
string strLimited;
string strUnLimited;
int nLenLimited = 0;
int nLenUnLimited = 0;
long long llMolecule = 0;
long long llDenominator = 0;
int nLimited = 0;
int nUnLimited = 0;
long long llGcd = 0;
double x = 10;//指数的底数
string::size_type Start = strNum.find('(');
if (Start != strNum.npos)//找到
{
string::size_type End = strNum.find(')',Start);
//取出两部分字符串
strLimited = strNum.substr(2,Start - 2);
strUnLimited = strNum.substr(Start + 1,End - Start - 1);
//获得两部分字符串的长度
nLenLimited = strLimited.size();
nLenUnLimited = strUnLimited.size();
assert(nLenLimited > 0 && nLenUnLimited > 0);
//获得两部分字符串对应的整数
nLimited = atoi(strLimited.c_str());
nUnLimited = atoi(strUnLimited.c_str());
//求对应分数的分子和分母
llMolecule = static_cast<long long>(nLimited * (pow(x,nLenUnLimited) - 1) + nUnLimited);
llDenominator = static_cast<long long>(pow(x,nLenLimited) * (pow(x,nLenUnLimited) - 1));
llGcd = Gcd(llMolecule,llDenominator);
cout<<llMolecule / llGcd <<" / "<<llDenominator / llGcd<<endl;
}
else
{
strLimited = strNum.substr(2);
nLenLimited = strLimited.size();
llMolecule = atoi(strLimited.c_str());
llDenominator = static_cast<long long>(pow(x,nLenLimited));
llGcd = Gcd(llMolecule,llDenominator);
cout<<llMolecule / llGcd <<" / "<<llDenominator / llGcd<<endl;
}
}
int main()
{
//string str = "0.3333(3333)";
string str = "0.285714(285714)";
//string str = "0.33(3)";
//string str = "0.3(000)";
//string str = "0.25";
//string str = "0.30";
RepresentExactly(str);
system("pause");
return 1;
}