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

7-18 Decimal Equivalent of a Binary Number (10 分),第1张

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;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5658740.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存