(算法)精确表示小数

题目:

给定一个正整数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;
}
原文地址:https://www.cnblogs.com/AndyJee/p/4864892.html