/****************************************
将输入的二进制数转换为十进制数
110=6
***************************************/
#include <iostream>
#include <Windows.h>
using namespace std;
int POWER(int iBase, int iExponent) {//自定义函数,用来计算iBase的iExponent幂是多少
int iRes = 1;
while (iExponent) {
iRes = iRes * iBase;
iExponent--;
}
return iRes;
}
int main()
{
int iBase;//存入每次计算时的系数 0 还是1
int iExponent;//存入2次方的幂
char Num[128];//记录输入的二进制数,记录为字符格式
int iCout = 0;//统计总共有多少个字符
int iRes = 0;//转换的结果
int i = 0;//计数用
cout << "请输入二进制数值:";
cin >> Num;
while (Num[i] != '\0') {
iCout++;
i++;
}
//iCout = sizeof(Num);
for ( i = 0; i < iCout; i++) {
iBase = Num[i]-'0';
iExponent = iCout - 1 - i;
iRes += iBase*POWER(2, iExponent);
}
cout << iRes;
system("pause");
return 0;
}
运行结果截图如下: