您的位置:首页 > 其它

acm pku 1131 Octal Fractions

2011-08-23 16:11 316 查看
问题分析: 主要的思路是这样的。先将8进制的数转换成2进制的数,再将2进制的数转换成10进制的数。8进制向2进制转换很简单,1位八进制对应3位二进制。代码中的binary数组就是用来暂存二进制数的。那么如何将二进制转换成10进制呢?我们大家都知道是那一位二进制数(0或1)乘以2的-k次方。但是由于题目中指出:小数的位数没有限制,因此直接转换精度的问题就出现了。我们把2的-k次方转换成5的k次方除以10的k次方问题就解决了。程序中算5的幂次相乘的函数是getTempResult。这一部分要动一动脑子。其他的就没什么啦~

#include <iostream>

#include <string>

using namespace std;

const int N=3;

const int BASE=5;

const string AFFIX1=" [8] = 0.";

const string AFFIX2=" [10]";

int binary
;

void convertIntoBinary(char c)

{

        int temp=c-'0';

        for(int i=N-1;i>=0;i--)

        {

            binary[i]=temp%2;

            temp=temp/2;

        }

}

void getTempResult(int* tempResult,int pos)

{

    if(pos==0)

    {

        tempResult[0]=BASE;

        return;

    }

    int curPos=pos;

    int j=curPos-1;

    int m=0;

    while(j>=0)

    {

        m+=tempResult[j]*BASE;

        tempResult[curPos]=m%10;

        m=m/10;

        curPos--;

        j--;

    }

    tempResult[curPos]=m;

    return;

}

void addToDecimal(int* tempResult,int* decimal,int pos)

{

    int m=0;

    for(int i=pos;i>=0;i--)

    {

        m=tempResult[i]+decimal[i];

        decimal[i]=m%10;

        m=m/10;

        if(m>0)

        {

            decimal[i-1]+=m;

        }

    }

}

void printDecimal(int* decimal,int pos)

{

    pos--;

    while(decimal[pos]==0)

    {

        pos--;

    }

    for(int i=0;i<=pos;i++)

    {

        cout<<decimal[i];

    }

}

int main()

{

    string octal;

   // freopen("E:\\input.txt","r",stdin);

    while(cin>>octal)

    {

        int pos=0;

        int arraySize= (octal.size()-2)*3;

        int *tempResult=NULL;

        int *decimal=NULL;

        tempResult=new int[arraySize];

        decimal=new int[arraySize];

        memset(tempResult,0,arraySize*sizeof(int));

        memset(decimal,0,arraySize*sizeof(int));

        string::iterator it=octal.begin();

        it++;

        it++;

        for(;it!=octal.end();it++)

        {

            convertIntoBinary(*it);

            for(int i=0;i<N;i++)

            {

                getTempResult(tempResult,pos);

                if(binary[i]>0)

                {

                    addToDecimal(tempResult,decimal,pos);

                }

                pos++;

            }

        }

        cout<<octal<<AFFIX1;

        printDecimal(decimal,pos);

        cout<<AFFIX2<<endl;

        delete tempResult;

        delete decimal;

    }

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string iterator delete null ini c