//Convert binary to decimal.
#include <iostream> #include <string> #include<stdlib.h> //for exit() using namespace std; int M(string x); void error(); void main() { string binNum; int decNum; cout<<"Please enter any binary number"<<endl; cin>>binNum; decNum=M(binNum); cout<<"The binary number "<<binNum<<" is equivalent to " <<decNum<<" in the decimal system."<<endl; } int M(string x) { int n=x.size(); if(n==0) return 0; else if(x[n-1]=='0') { x.resize(n-1); return 2*M(x); } else if(x[n-1]=='1') { x.resize(n-1); return 2*M(x)+1; } else error(); } void error() { cout<<"ha ha you messed up!!!"<<endl; exit(1); }
#include<iostream> #include<string> using namespace std; int Mbin(string Bin); void main() { string num; int potatoe; cout<<"Enter binary number"<<endl; cin>>num; potatoe = Mbin(num); if(potatoe != -1) cout<<"the binary number of "<<num <<" is equal to "<<potatoe<<endl; } int Mbin(string Bin) { int n=Bin.size(); if(Bin=="1") return 1; else if(Bin == "0") return 0; else if(Bin[n-1]=='0') { Bin.resize(n-1); return 2*Mbin(Bin); } else if(Bin[n-1]=='1') { Bin.resize(n-1); return 2*Mbin(Bin)+1; } else { cout<<"You did not enter a binary number"<<endl; return -1; } }