【rlz02】二进制转十进制

Time Limit: 3 second
Memory Limit: 2 MB

问题描述

输入一个二进制数,编程转换为十进制数。
整数部分不会超过65535,二进制的小数部分不会超过4位。

Sample Input

1111111111111111
Sample Output

65535
Sample Input

1.1
Sample Output

1.5

【题目链接】:http://noi.qz5z.com/viewtask.asp?id=rlz02

【题解】

二进制小数的权依次为10^-1,10^-2….
输出的话,不能直接cout;
要加个setprecision(x);
x是”有效数字”;不加的话默认为6;(浮点数);
2222222222222222222会写成6个2然后乘Exx的形式;
2222.0222的话只会保留2222.02;
头文件是iomanip

【完整代码】

//#include <bits/stdc++.h>
#include <cstdio>
#include <string>
#include <iostream>
#include <iomanip>

using namespace std;

string s;

int main()
{
    //freopen("F:\\rush.txt","r",stdin);
    cin >> s;
    int pos = s.find('.',0);
    if (pos!=-1)
    {
        int num = 1;
        int zhengshu = 0;
        for (int i = pos-1;i >= 0;i--)
        {
            if (s[i]=='1')
                zhengshu+=num;
            num*=2;
        }
        double num1 = 0.5,xiaoshu = 0;
        int len = s.size();
        for (int i = pos+1;i <= len-1;i++)
        {
            if (s[i]=='1')
                xiaoshu+=num1;
            num1*=0.5;
        }
        int lo;
        double temp = 0;
        temp = zhengshu;
        temp+=xiaoshu;
        cout <<setprecision(9)<<temp<<endl;
    }
    else
    {
        int num = 1;
        int zhengshu = 0,len = s.size();
        for (int i = len-1;i >= 0;i--)
        {
            if (s[i]=='1')
                zhengshu+=num;
            num*=2;
        }
        printf("%d\n",zhengshu);
    }
    return 0;
}
posted @ 2017-10-04 18:45  AWCXV  阅读(192)  评论(0编辑  收藏  举报