acm pku 1131 Octal Fractions

来源:互联网 发布:一楼土木人淘宝假货 编辑:程序博客网 时间:2024/05/18 02:47

问题分析: 主要的思路是这样的。先将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[N];


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;
}
原创粉丝点击