NYOJ 647 奋斗小蜗牛在请客【模拟】

原题链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=647

思路:没啥说的,本想用java写,没找到double进制转换的对应函数。。就该用c++,本想偷懒下,直接用string,然后找个string转化double的函数,最后还是失败了 用sstream,格式会变。。发现其实最简单的方法就是直接用数组模拟。。一直想偷懒下,结果绕了一个圈。。。

先提供个double型化二进制的模版,这里不考虑格式。。

#include<sstream>
#include<stdlib.h>
#include<algorithm>
#include<iostream>
using namespace std;
string::iterator it;
string Trans(long Integer)
{
    if(Integer == 0) return "0";
    string temp="";
    while(Integer)
    {
        temp = char(Integer%2+48)+temp;
        Integer/=2;
    }
    return temp;
}
string Trans(double Decimal)
{
    string temp=".";
    int n = 20;
    while(Decimal&&n)
    {
        Decimal*=2;
        temp = temp + char(int(Decimal)+48);
        Decimal = Decimal - int(Decimal);
        n--;
    }
    return temp;
}
int main()
{
    int i,j;
    double x;
    while(cin>>x)
    {
        long Integer = long(x);
        double Decimal = x-Integer;
        double ans;
        string Ans = Trans(Integer) + Trans(Decimal);
        cout<<Ans<<endl;
    }
}

本题AC代码:

#include<sstream>
#include<stdlib.h>
#include<algorithm>
#include<iostream>
using namespace std;
string::iterator it;
string Trans(long Integer)
{
    if(Integer == 0) return "0";
    string temp="";
    while(Integer)
    {
        temp = char(Integer%2+48)+temp;
        Integer/=2;
    }
    return temp;
}
string Trans(double Decimal)
{
    string temp=".";
    int n = 20;
    while(Decimal&&n)
    {
        Decimal*=2;
        temp = temp + char(int(Decimal)+48);
        Decimal = Decimal - int(Decimal);
        n--;
    }
    return temp;
}
int main()
{
    int i,j;
    double x;
    while(cin>>x)
    {
        long Integer = long(x);
        double Decimal = x-Integer;
        double ans;
        string Ans = Trans(Integer) + Trans(Decimal);
        //cout<<Ans<<endl;
        
        /*根据题目进行的格式控制、、*/
        int n = Ans.length();
        while(--n)
        {
            it = Ans.end()-1;
            if(Ans[n] == '0') 
                Ans.erase(it);
            else if(Ans[n] == '.')
            {
                Ans.erase(it);
                break;
            }
            else
                break;
        }
        cout<<Ans<<endl;
        /*
        stringstream ss;
        ss<<Ans;
        ss>>ans;
        ss.clear();
        cout<<ans<<endl;
        */
    }
}
点赞