如何创建二进制到十进制程序?

时间:2015-08-09 02:39:53

标签: c++ algorithm

需要制作二进制到十进制的程序,这是我来的最远:

二进制101110应该以十进制表示46。但这打印出来11.感谢任何帮助。

我的代码:

#include <iostream>
using namespace std;

int binary_to_number(int binary_digits[], int number_of_digits)
{
    int sum = 0;
    int n = -1;
    int i = 0;

    for ( i = number_of_digits - 1; i >= 0; i--){
            n++;

            if (binary_digits[i] == 1)
                sum = sum + (2^n);
    }
    return sum;
}

#ifndef WEBSUBMIT
int main()
{
     int binary_digits[6] = {1,0,1,1,1,0};
     cout << "" << binary_to_number(binary_digits, 6) << endl;
}
#endif //WEBSUBMIT

1 个答案:

答案 0 :(得分:0)

以下是重写代码:

#include <iostream>
using namespace std;

int binary_to_number(int binary_digits[], int number_of_digits)
{
    int sum = 0;
    int i = 0;
    int cnt = number_of_digits;


    for (i = 0; i < number_of_digits; i++) {
        cnt--;

        if (binary_digits[i] == 1)
            sum = sum + pow(2, cnt);

    }
    return sum;
}

#ifndef WEBSUBMIT
int main()
{
    int binary_digits[6] = { 1, 0, 1, 1, 1, 0 }; //46
    cout << "" << binary_to_number(binary_digits, 6) << endl;
    system("PAUSE");
}
#endif //WEBSUBMIT

binary_digits [0]为1否0 binary_digits [0]是2 ^ 5

int binary_digits[6] = { 1, 0, 1, 1, 1, 0 };