每日一题(78) - 精确表达浮点数
2013-08-20 22:58
169 查看
题目来自编程之美
题目:
举例:
0.3333(3333) = 1/3
0.285714(285714) = 2/7
0.3(000) = 3/10
0.25 = 1/4
思路:
代码:
注意:假设输入的参数形式为0.XXXX的形式,且均为正数。
题目:
举例:
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; }
相关文章推荐
- 编程之美 2.6 精确表达浮点数
- 精确表达浮点数
- 编程之美 精确表达浮点数
- 2.6 精确表达浮点数
- 编程之美2.6精确表达浮点数Java版
- 浮点数(有限浮点数、无限循环浮点数)的精确表达
- 精确表达浮点数
- 《编程之美》学而思-精确表达浮点数
- 精确表达浮点数
- 编程之美:精确表达浮点数
- 商业应用中Java浮点数的精确计算及表示
- JavaScript 创建用于对象的模板【每日一段代码78】
- 更精确地使用浮点数(银行或金融行业)
- 【编程之美】2.6 精确表达浮点数
- 浮点数的精确误差
- 商业应用中Java浮点数的精确计算及表示
- 精确表达浮点数
- 确定double型浮点数能精确到小数点后几位
- Java的简单类型进行精确的浮点数运算
- 每日一得--解决tomcat 5.5 不能识别 JSP的EL表达,但tomcat 7.0 可以的问题