首页 > 编程语言 > 详细

(算法)精确表示小数

时间:2015-10-09 19:54:31      阅读:222      评论:0      收藏:0      [点我收藏+]

题目:

给定一个正整数n,求1/n的小数表示,如:

1/2=0.5

1/3=0.(3)

1/6=0.1(6)

1/7=0.(142857)

其中括号表示小数中的循环部分。

思路:

考虑一下除法运算的过程:

当余数与之前运算出现重复时,那么说明循环已经开始,因此可以通过hash表来记录余数对应的位置。

被除数  除数  余数  商

1     7   1   0

1*10         7   3   1 

3*10      7    2   4

2*10    7    6     2       

6*10      7    4   8

4*10    7    5   5 

5*10         7   1   7 

1*10         7   3   1 

3*10      7    2   4

2*10    7    6     2       

6*10      7    4   8

4*10    7    5   5 

5*10         7   1   7 

代码:

#include<iostream>
#include<map>
#include<sstream>
using namespace std;

string decimalRepresent(int n){
    map<int,int> mp;
    int num=10;
    int residue=1;
    string multi;
    int idx=0;


    while(mp.find(residue)==mp.end()){
        if(residue==0){
            stringstream ss;
            string tmp;
            ss<<1.0/n;
            ss>>tmp;
            return tmp;
        }

        mp[residue]=idx;

        stringstream sstr;
        string str;
        sstr<<num/n;
        sstr>>str;
        multi=multi+str;
        idx++;
    
        residue=num%n;
        num=residue*10;
    }
    
    string result="0."+multi.substr(0,mp[residue])+"("+multi.substr(mp[residue])+")";
    return result;
}

int main(){
    int n;
    while(cin>>n){
        cout<<"The result of 1/"<<n<<": "<<endl;
        cout<<decimalRepresent(n)<<endl;
    }

    return 0;
}

 

(算法)精确表示小数

原文:http://www.cnblogs.com/AndyJee/p/4864892.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!