大神们,过来改错了。利用栈的逆波兰表达式的24点游戏
时间: 2017-02-05来源:开源中国
前景提要
HDC调试需求开发(15万预算),能者速来!>>>
给定4张扑克牌,【1-10】;
用加减乘除计算出24 #include<iostream> #include<string> #include<cstring> #include<cstdlib> //#include<cstdio> #include<exception> #include<stack> using namespace std; string rand_op() { int n=int(rand()/double(RAND_MAX)*4);//[0,1] //0-1,1-2,2-3,3-4 //cout<<n<<" "; if(n==0) return "+"; else if(n==1) return "-"; else if(n==2) return "*"; else return "/"; } void shuffle(string* ss) { /* int n=0; cout<<n; for(int j=0;!ss[j].empty();j++){ n++; } cout<<n; */ for(int i=0;i<7;i++) { int k=int(rand()/double(RAND_MAX)*7); string str=ss[i]; ss[i]=ss[k]; ss[k]=str; } } int op(int a,int b,string oper) { char ch='A'; cout<<"check--op"; int sum; if(oper=="+") sum=a+b; else if(oper=="-") sum=a-b; else if(oper=="*") sum=a*b; else { if(a%b != 0){ //throw new exception("not/"); throw ch; } else sum=a/b; } return sum; } int ji_suan(string* ss) { stack<string>stk; /*测试注释 for(int j=0;j<7;j++) { stk.push(ss[j]); cout<<ss[j]<<" "; } cout<<endl; while(!stk.empty()) { string str=stk.top(); cout<<str<<" "; stk.pop(); } cout<<endl; */ try{ for(int i=0;i<7;i++) { if(ss[i]=="+" || ss[i]=="-" || ss[i]=="*" || ss[i]=="/" ){ //cout<<"check "; //cout<<stk.top(); int a=atoi(stk.top().c_str()); stk.pop(); //cout<<stk.top(); int b=atoi(stk.top().c_str()); stk.pop(); stk.push( op(a,b,ss[i])+" " ); }else{ stk.push(ss[i]); } } } catch(char){ return 0; } if(stk.size()==1 && stk.top()=="24") return 1; else return 0; } void show(string *ss) { stack<string>stk; for(int i=0;i<7;i++) { if(ss[i]=="+" || ss[i]=="-" || ss[i]=="*" || ss[i]=="/" ){ string str1=stk.top(); stk.pop(); string str2=stk.top(); stk.pop(); stk.push("(" +str1+ss[i]+str2+" )"); }else{ stk.push(ss[i]); } } } void f(string* ss) { //随机产生组合序列,计算结果为24返回结果 //逆波兰表达式 for(int k=0;k<10;k++) { int i; string* buf=new string[7]; for( i=0;i<4;i++) buf[i]=ss[i]; for( i=4;i<7;i++) buf[i]=rand_op(); shuffle(buf);//洗牌,不能用next_permutation //char ch; //ch=getchar(); if(ji_suan(buf)==1){ cout<<"ok"<<endl; show(buf); } } } int main() { while(1){ cout<<"输入4个整数: "; string * x =new string[4]; for(int i=0;i<4;i++){ cin>>x[i]; } f(x); } return 0; }

科技资讯:

科技学院:

科技百科:

科技书籍:

网站大全:

软件大全:

热门排行