栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

7-18 Decimal Equivalent of a Binary Number (10 分)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

7-18 Decimal Equivalent of a Binary Number (10 分)

Input an integer containing only 0s and 1s (i.e., a “binary” integer) and print its decimal equivalent.

[Hint: Use the remainder and division operators to pick off the “binary” number’s digits one at a time from right to left. Just as in the decimal number system, in which the rightmost digit has a positional value of 1, and the next digit left has a positional value of 10, then 100, then 1000, and so on, in the binary number system the rightmost digit has a positional value of 1, the next digit left has a positional value of 2, then 4, then 8, and so on. Thus the decimal number 234 can be interpreted as4 * 1 + 3 * 10 + 2 * 100 . The decimal equivalent of binary 1101= 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 ]

Input Specification:

Input an integer containing only 0s and 1s.

Output Specification:

Print its decimal equivalent of binary (1101 = 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 ). After showing the number, seperate each number and symbol by ong space.

Sample Input:
1001101

结尾无空行

Sample Output:
1001101 = 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 + 0 * 16 + 0 * 32 + 1 * 64

结尾无空行

作者sunjun单位武汉理工大学代码长度限制16 KB时间限制400 ms内存限制64 MB

答案:

#include
#include
#include
#include
using namespace std;

int main(){
    char str[10];
    cin >> str;
    char cha[10] = {0};
    strcpy(cha,str);
    string str2 = " * ";
    string str3 = " + ";
    string str1[10];
    for(int i=strlen(str)-1,j=0; i>=0,j<=strlen(str)-1; i--,j++){      
        if(j != strlen(str)-1){
            str1[j] += cha[i];
            str1[j] += str2;
            str1[j] += std::to_string((int)pow(2,j));
            str1[j] += str3;
        }else{
            str1[j] += cha[i];
            str1[j] += str2;
            str1[j] += std::to_string((int)pow(2,j));
        }
    }
    cout << str << " = ";
    for(int i=0; i<=strlen(str); i++)
        cout << str1[i];
    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/656660.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号