输入一个2进制数转换成10进制输出—循环练习9
*#include #include <Windows.h> #include using namespace std; int main(void) { string str; //二进制数据 int q = 0; // int p = 1; cout << "请输入一个人二进制数据: "; cin >> str; for(int i=str.length()-1; i>=0; --i) { int j = str[i] - '0'; q += j*p; p *= 2; } cout << "q==" << q << endl; /** for (int i=str.length()-1; i>=0; i--) { int x = str[i] - '0'; s += x * p; p *= 2; } //假设:str = 1010 s = 0 p = 1 x = 0 // 1. 0-0 = 0 x = 0 // 2. 0*1 = 0 s = 0 0+0= 0=s // 3. 1*2 = 2 p = 2 // s = 0 p = 2 // 1. 1-0 = 1 x = 1 // 2. 1*2 = 2 s = 2 0+2= 2=s // 3. 2*2 = 4 p = 4 // s = 2 p = 4 // 1. 0-0 = 0 x = 0 // 2 . 0*4 = 0 s = 2