利用棧結構二進位制數轉十進位制數程式碼實現c++
阿新 • • 發佈:2019-02-09
#include<string> #include<iostream> #include<cmath> #define MAXLEN 50 using namespace std; struct StackType{ char data[MAXLEN]; int top; }; StackType*STInit() { StackType*s; if(s=new StackType){ s->top=0; return s; } return NULL; } StackType*STPush(StackType*s,char e){ if(s->top==MAXLEN) cout<<"棧溢位!"<<endl; s->data[++s->top]=e; return s; } char STPop(StackType*s){ if(s->top==0){ cout<<"棧為空!"<<endl; exit(0); } return s->data[s->top--]; } int main() { StackType*s; int i,len,sum=0; char e,h; cout<<"請輸入二進位制數:"<<endl; s=STInit(); cin>>e; while(e!='#'){ STPush(s,e); cin>>e; } len=s->top; for(i=0;i<len;i++){ sum=sum+(STPop(s)-48)*pow(2,double(i)); } cout<<sum<<endl; system("pause"); return sum; }