每日一题(78) - 精确表达浮点数

题目来自编程之美

题目:


举例:

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值