24点游戏C++ 代码
C语言写的24点游戏
if((m%4)==0&&newp[j]%newp[q]==0&&c==3&&newp[q+1]%s2==0)
printf("%d%c((%d%c%d)%c%d)=%d\n",p[3],p1[2],p[0],p1[0],p[1],p1[1],p[2],s3);
}
}
}
}
}
}
}
}
for(c=0;c<4;c++)
{
switch(b[c])
{
case 1:s3=s2+newp[q+1];sign='+';break;
case 2:s3=s2-newp[q+1];sign='-';break;
int a[4],newp[4],b[4]={1,2,3,4};//a[4]数组存放随机生成的四个数
char p1[3],sign; //定义存储运算符的字符数组
printf("四个数是:");
for(i=0;i<4;i++)
{
a[i]=rand()%13+1; //获得随机数
printf("(%d%c%d)%c(%d%c%d)=%d\n",p[2],p1[2],p[3],p1[1],p[0],p1[0],p[1],s3);
else
printf("(%d%c%d)%c(%d%c%d)=%d\n",p[0],p1[0],p[1],p1[1],p[2],p1[2],p[3],s3);
经典游戏--24点--c++代码实现和总体思路(简单暴力向)
经典游戏--24点--c++代码实现和总体思路(简单暴⼒向)24点 24点是⼀个⾮常经典的游戏,从扑克牌⾥抽4张牌,其中J=11,Q=12,K=13,然后经过+,-,*,/,(),的计算后,使得计算得值为24,例如抽到1,2,2,5四张牌,那么 (1+5)*(2+2)=24; 这就是可以凑成24点的⼀种情况,作为⼀个经典题⽬,在leetcode上也有对应的题⽬进⾏练习 PS 看见知乎⼤佬有⼀种必24点的算法,但是要⽤到阶乘和次⽅式⼦为(a0+b0+c0+d0)! =24⼀、总体思路 1.因为是简单暴⼒向的,所以我们的做法就是直接穷举出所有可能的情况,⾸先是考虑四个数a,b,c,d的排列情况 如b,a,c,d等等,通过排列组合可以得到 4*3*2*1 = 24 种情况 2.然后考虑a,b,c,d中的三个运算符的情况设⼀个⾃定义的运算符为,可以是+,-,*,/中的任意⼀个 则有 a b c$d 这个式⼦,同样,运算符的可能性有 3*4 = 12 种 3.最后考虑()的情况,我们规定,每次⼀对()只框住两个数,⽐如a+b+c+d =(((a+b)+c)+d) = ((r1+c)+d)=(r2+d)=r3(其中r1=a+b,r2=r1+c,r3=r2+d) ()的情况其实就是运算优先级的问题,⽆论运算符是什么,都⼀定是先运算括号⾥的内容 所以我们可以穷举出情况 第⼀种r1=a b,r2=r1c,r3=r2$d; 第⼆种r1=b c,r2=a r1,r3=r2$d; 第三种r1=b c,r2=r1d,r3=a$r2; 第四种r1=c d,r2=b r1,r3=a$r2; 第五种r1=a b,r2=c d,r3=r1$r2; 仔细观察不难发现,我们控制了运算符和数字的绝对顺序从左到右的顺序严格是a b c$d,不论任何情况都不会改变abcd的顺序,是因为我们在上⾯已经排出来了所有的24种情况,所以我们这就可以严格控制abcd的顺序了⼆、代码实现1 #include <iostream>2 #include <string>3using namespace std;4int mark_int[4] = { 1,2,3,4 };5string mark_char = "+-*/";6double cal(double a, int m, double b)7 {8switch (m)9 {10case1: return a + b;11case2: return a - b;12case3: return a * b;13case4: return a / b;14 }15 }1617bool cal1(double a, double b, double c, double d, int m1, int m2, int m3)18 {19double r1;20double r2;21double r3;22 r1 = cal(a, m1, b);25if (r3 == 24)26 {27 cout << "(((" << a << mark_char[m1 - 1] << b << ")" << mark_char[m2 - 1] << c << ")" << mark_char[m3 - 1] << d << ")" << endl;28return1;29 }30return0;31 }3233bool cal2(int a, int b, int c, int d, int m1, int m2, int m3)34 {35double r1;36double r2;37double r3;38 r1 = cal(b, m1, c);39 r2 = cal(a, m2, r1);40 r3 = cal(r2, m3, d);41if (r3 == 24)42 {43 cout << "((" << a << mark_char[m1 - 1] << "(" << b << mark_char[m2 - 1] << c << "))" << mark_char[m3 - 1] << d << ")" << endl;44return1;45 }46return0;47 }4849bool cal3(int a, int b, int c, int d, int m1, int m2, int m3)50 {51double r1;52double r2;53double r3;54 r1 = cal(b, m1, c);55 r2 = cal(r1, m2, d);56 r3 = cal(a, m3, r2);57if (r3 == 24)58 {59 cout << "(" << a << mark_char[m1 - 1] << "((" << b << mark_char[m2 - 1] << c << ")" << mark_char[m3 - 1] << d << "))" << endl;60return1;61 }62return0;63 }6465bool cal4(int a, int b, int c, int d, int m1, int m2, int m3)66 {67double r1;68double r2;69double r3;70 r1 = cal(c, m1, d);71 r2 = cal(b, m2, r1);72 r3 = cal(a, m3, r2);73if (r3 == 24)74 {75 cout << "(" << a << mark_char[m1 - 1] << "(" << b << mark_char[m2 - 1] << "(" << c << mark_char[m3 - 1] << d << ")))" << endl;76return1;77 }78return0;79 }8081bool cal5(int a, int b, int c, int d, int m1, int m2, int m3)82 {83double r1;84double r2;85double r3;86 r1 = cal(a, m1, b);87 r2 = cal(c, m3, d);88 r3 = cal(r1, m2, r2);89if (r3 == 24)90 {91 cout << "((" << a << mark_char[m1 - 1] << b << ")" << mark_char[m2 - 1] << "(" << c << mark_char[m3 - 1] << d << "))" << endl;92return1;93 }94return0;95 }969798bool all_cal(int a, int b, int c, int d)99 {100for (int i = 1; i <= 4; i++)101for (int j = 1; j <= 4; j++)102for (int k = 1; k <= 4; k++)103 {104if (cal1(a, b, c, d, i, j, k) == true || cal2(a, b, c, d, i, j, k) == true || cal3(a, b, c, d, i, j, k) == true || cal4(a, b, c, d, i, j, k) == true || cal5(a, b, c, d, i, j, k) == true) 105return1;106 }107return0;108 }110111bool judge(int a, int b, int c, int d)112 {113int all[24][4] = {114 {a,b,c,d},{a,b,d,c},{a,c,b,d},{a,c,d,b},{a,d,b,c},{a,d,c,b},115 {b,a,c,d},{b,a,d,c},{b,c,a,d},{b,c,d,a},{b,d,a,c},{b,d,c,a},116 {c,a,b,d},{c,a,d,b},{c,b,a,d},{c,b,d,a},{c,d,a,b},{c,d,b,a},117 {d,a,b,d},{d,a,d,b},{d,b,a,c},{d,b,c,a},{d,c,a,b},{d,c,b,a},118 };119for (int i = 0; i < 24; i++)120 {121if (all_cal(all[i][0], all[i][1], all[i][2], all[i][3]))122return1;123 }124return0;125 }126127int main()128 {129int a, b, c, d;130 cin >> a >> b >> c >> d;131if (!judge(a, b, c, d))132 cout << "凑不成24点" << endl;133134 }三、代码解释先做⼀个计算两个数的函数,⽤数组int mark_int[4] = {1,2,3,4}的四个数表⽰+ - * /,string mark_char是⽤来最后显⽰的1int mark_int[4] = { 1,2,3,4 };2string mark_char = "+-*/";3double cal(double a, int m, double b)4 {5switch (m)//⽤switch来进⾏运算符的选择6 {7case1: return a + b;8case2: return a - b;9case3: return a * b;10case4: return a / b;11 }12 }我们在实现五种括号的函数,并且我们规定运算⼀定是 a m1 b m2 c m3 d(m1,m2,m3是三个运算符的代号),意思就是abcd的从左到右顺序不乱,m1m2m3从左到右的顺序也不会乱,⽐较粗暴的理解就是ab之间⼀定是m1,bc之间⼀定是m2,cd之间⼀定其实m3,然后如果成功返回运算的过程和true,否则返回false1bool cal1(double a, double b, double c, double d, int m1, int m2, int m3)2 {3double r1;4double r2;5double r3;6 r1 = cal(a, m1, b);7 r2 = cal(r1, m2, c);8 r3 = cal(r2, m3, d);9if (r3 == 24)10 {11 cout << "(((" << a << mark_char[m1 - 1] << b << ")" << mark_char[m2 - 1] << c << ")" << mark_char[m3 - 1] << d << ")" << endl;12return1;13 }14return0;15 }//第⼀种r1=a$b,r2=r1$c,r3=r2$d;1617bool cal2(int a, int b, int c, int d, int m1, int m2, int m3)18 {19double r1;20double r2;21double r3;22 r1 = cal(b, m1, c);23 r2 = cal(a, m2, r1);24 r3 = cal(r2, m3, d);25if (r3 == 24)26 {27 cout << "((" << a << mark_char[m1 - 1] << "(" << b << mark_char[m2 - 1] << c << "))" << mark_char[m3 - 1] << d << ")" << endl;28return1;29 }30return0;31 }//第⼆种r1=b$c,r2=a$r1,r3=r2$d;33bool cal3(int a, int b, int c, int d, int m1, int m2, int m3)34 {35double r1;36double r2;37double r3;38 r1 = cal(b, m1, c);39 r2 = cal(r1, m2, d);40 r3 = cal(a, m3, r2);41if (r3 == 24)42 {43 cout << "(" << a << mark_char[m1 - 1] << "((" << b << mark_char[m2 - 1] << c << ")" << mark_char[m3 - 1] << d << "))" << endl;44return1;45 }46return0;47 }//第三种r1=b$c,r2=r1$d,r3=a$r2;4849bool cal4(int a, int b, int c, int d, int m1, int m2, int m3)50 {51double r1;52double r2;53double r3;54 r1 = cal(c, m1, d);55 r2 = cal(b, m2, r1);56 r3 = cal(a, m3, r2);57if (r3 == 24)58 {59 cout << "(" << a << mark_char[m1 - 1] << "(" << b << mark_char[m2 - 1] << "(" << c << mark_char[m3 - 1] << d << ")))" << endl;60return1;61 }62return0;63 }//第四种r1=c$d,r2=b$r1,r3=a$r2;6465bool cal5(int a, int b, int c, int d, int m1, int m2, int m3)66 {67double r1;68double r2;69double r3;70 r1 = cal(a, m1, b);71 r2 = cal(c, m3, d);72 r3 = cal(r1, m2, r2);73if (r3 == 24)74 {75 cout << "((" << a << mark_char[m1 - 1] << b << ")" << mark_char[m2 - 1] << "(" << c << mark_char[m3 - 1] << d << "))" << endl;76return1;77 }78return0;79 }//第五种r1=a$b,r2=c$d,r3=r1$r2;接下来是12种的符号的排列情况,如果有⼀种括号情况满⾜,我们就返回true,否则返回false1bool all_cal(int a, int b, int c, int d)2 {3for (int i = 1; i <= 4; i++)4for (int j = 1; j <= 4; j++)5for (int k = 1; k <= 4; k++)6 {7if (cal1(a, b, c, d, i, j, k) == true || cal2(a, b, c, d, i, j, k) == true || cal3(a, b, c, d, i, j, k) == true || cal4(a, b, c, d, i, j, k) == true || cal5(a, b, c, d, i, j, k) == true) 8return1;9 }10return0;11 }最后是在总判断函数中写⼊24种的abcd排列情况1bool judge(int a, int b, int c, int d)2 {3int all[24][4] = {4 {a,b,c,d},{a,b,d,c},{a,c,b,d},{a,c,d,b},{a,d,b,c},{a,d,c,b},5 {b,a,c,d},{b,a,d,c},{b,c,a,d},{b,c,d,a},{b,d,a,c},{b,d,c,a},6 {c,a,b,d},{c,a,d,b},{c,b,a,d},{c,b,d,a},{c,d,a,b},{c,d,b,a},7 {d,a,b,d},{d,a,d,b},{d,b,a,c},{d,b,c,a},{d,c,a,b},{d,c,b,a},8 };9for (int i = 0; i < 24; i++)10 {11if (all_cal(all[i][0], all[i][1], all[i][2], all[i][3]))12return1;13 }14return0;15 }主函数调⽤judge就完成整个算法了✿✿ヽ(°▽°)ノ✿1int main()4 cin >> a >> b >> c >> d;5if (!judge(a, b, c, d))6 cout << "凑不成24点" << endl;78 }失败的话会显⽰“凑不成24点”其实这个算法的话我写的可以说基本没有优化,就是枚举所有情况实现的,csdn上有⼤佬是有更好的思路的,这篇⽂章也是看了csdn的⼤佬的代码然后⾃⼰修修补补写出来的(我原来看的那篇有bug,⼤佬⾃⼰没发现好像。
C程序设计24点小游戏
C程序设计24点小游戏第一篇:C程序设计 24点小游戏1设计内容有2、3、4、5、6、7、8、9、10、J、Q、K、A共13张牌,编一程序,判断对任意给定的4张牌,能否在进行加、减、乘、除运算后,其运算结果等于24。
其中J按11计算,Q按12计算,K按13计算,A按1计算。
如果能得到结果24,则输出可得到该结果的计算表达式。
若输入数据符合要求,且经过加、减、乘、除运算后,运行结果能得到24,如输入5,5,5,1,则显示可得到该结果的计算表达式,如5*(5-(1/5))。
若输入数据小于1或者大于13或者不是整数时,提示输入错误。
若输入不能运算出24的数据,如1,1,1,1,则显示经过加、减、乘、除运算后,运行结果不能得到24。
2程序设计2.1存储结构设计由于要储存的数据不多,主要是储存所输入的4个整数,所以采用一维数组(a[4])储存。
而计算过程会出现小数,所以数据类型采用浮点型(float)。
2.2主要程序设计程序采用穷举法,对输入的4个数进行排列,有4!=24种。
用for来循环,if来判断,算法如下。
for(i=0;i<4;i++)for(j=0;j<4;j++)if(j!=i)for(k=0;k<4;k++)if(k!=j&& k!=i)for(l=0;l<4;l++)if(l!=i && l!=j && l!=k){ calculate(a[i],a[j],a[k],a[l]);}用if来判断括号的类型,然后作出不同顺序的运算。
括号有两对,主要有两种类型:一种是()()型,如(a+b)*(c+d);另一种是(())型,继续细分又有种类型,如下a*(b*(c+d)),(a*(b+c))*d,a*((b+c)*d),((a+b)*c)*d。
算法如下if((!(i==3 && b==0))&&(!(j==3 && c==0))&&(!(k==3 && d==0))){ sum1=arithmetic(i,a,b);sum2=arithmetic(j,sum1,c);sum 3=arithmetic(k,sum2,d);}if(k==2){ sum1=arithmetic(i,a,b);sum2=arithmetic(j,c,d);sum3=s um1*sum2;}if(k==3){ sum1=arithmetic(i,a,b);sum2=arithmetic(j,c,d);if(sum2! =0){ sum3=sum1/sum2;} } 在输入方面,按要求,数据类型是1 至13 的整数,符合则进行运算,不符合则重新输入。
c语言实现24点游戏
#include "stdio.h"#include "math.h"#include "time.h"void main(){void first();void second();int third();time_t t; /设置机器时间int close=0;char get;clrscr();/清除屏幕缓冲区及液晶显示缓冲区光标位置回到屏幕左上角。
srand((unsigned) time(&t)); /系统时间来初始化for(;;){clrscr();清除屏幕缓冲区及液晶显示缓冲区光标位置回到屏幕左上角printf("24 POINTS SYSTEM v2.2\n"); printf("MADE BY DANTE WANG\n");printf("Jul.28th 2006\n\n");printf("Please choose mode!\n\n");printf("1. Game Mode\n");printf("2. Count Mode\n");printf("3. Quit\n\n");get=getch();等待你按下任意键之后,把该键字符所对应的ASCII码赋给ch,再执行下面的语句switch(get){case '1': first(); break;case '2': second();break;case '3': close=third(); break;default: printf("Please input 1, 2 or 3!\n"); getch(); }if(close)break;}}void first(){int jdgsgn(int a,int b,int c,int d); 1)统计出求不出24的所有组合数目(2)将每一种组合的计算结果写入文件result.txt,每两个组合占一行。
24点游戏C语言代码及报告
24点游戏C语言代码及报告24点游戏一,问题分析二十四点游戏规则:给出4个数字,所给数字均为有理数,用加、减、乘、除(可加括号)把给出的数算成24(每个数必须用一次且只能用一次,先算出结果者获胜。
步骤:比如下面的例子:例:3、8、8、9,答案1:(9—8)×8×3答案2: 3×8 ?(9—8)答案3:(9—8?8)×3利用3×8,24、4×6,24求解我的主要想法是首先穷举的可行性问题。
我把表达式如下分成三类—— 1、无括号的简单表达式。
2、有一个括号的简单表达式。
3、有两个括号的较复4、杂表达式。
穷举的开始我对给出的四个数进行排列,其可能的种数为4*3*2*1=24。
我利用一个嵌套函数实现四个数的排列二,源程序及注释//首先穷举的可行性问题。
我把表达式如下分成三类——//1、无括号的简单表达式。
//2、有一个括号的简单表达式。
//3、有两个括号的较复4、杂表达式。
//穷举的开始我对给出的四个数进行排列,其可能的种数为4*3*2*1=24。
我利用一个嵌套函数实现四个数的排列#include <iostream>#include <string>using namespace std;int number=0;string sss[5000];float cal(float a,float b,int p) {switch(p){case 1:return a+b;case 2:return a-b;case 3:return a*b;case 4:return a/b;case 5:return b-a;case 6:return b/a;}}string link(string a,string b,int p) {string st=a;switch(p){case 1:st+=("+"+b);break;case 2:st+=("-"+b);break;case 3:st+=("*"+b);break;case 4:st+=("/"+b);break;case 5:st=b+"-"+st;break;case 6:st=b+"/"+st;break;}st="("+st+")";return st;}void putout1(string c[],int p[]) { string st;st=link(c[1],c[2],p[1]);st=link(st,c[3],p[2]);st=link(st,c[4],p[3]);st=st.erase(0,1);st=st.erase(st.length()-1,1); number++;sss[number]=st;}void putout2(string c[],int p[]) { string st1,st2,st;st1=link(c[1],c[2],p[1]);st2=link(c[3],c[4],p[3]);st=link(st1,st2,p[2]);st=st.erase(0,1);st=st.erase(st.length()-1,1);number++;sss[number]=st;}void suan(float a[],string c[]) {int p[4];int i;float sum,sum1,sum2;for(p[1]=1;p[1]<=6;p[1]++)for(p[2]=1;p[2]<=6;p[2]++)for(p[3]=1;p[3]<=6;p[3]++){sum=cal(a[1],a[2],p[1]);sum=cal(sum,a[3],p[2]);sum=cal(sum,a[4],p[3]);if((sum-24>=0&&sum-24<1e-5)||(sum-24<=0&&sum-24>-1e-5)) putout1(c,p); sum1=cal(a[1],a[2],p[1]);sum2=cal(a[3],a[4],p[3]);sum=cal(sum1,sum2,p[2]);if((sum-24>=0&&sum-24<1e-5)||(sum-24<=0&&sum-24>-1e-5)) putout2(c,p); }}void disorder(float a[],string c[]){float b[5];string d[5];int i,j,k,l;for(i=1;i<=4;i++)for(j=1;j<=4;j++){if(j==i)continue;for(k=1;k<=4;k++){if(k==i||k==j)continue;for(l=1;l<=4;l++){if(l==i||l==j||l==k)continue;b[1]=a[i];b[2]=a[j];b[3]=a[k];b[4]=a[l]; d[1]=c[i];d[2]=c[j];d[3]=c[k];d[4]=c[l]; suan(b,d);}}}}int main(){cout<<"请输入四个数字";float a[5];int i,j;string c[5];for(i=1;i<=4;i++){cin>>a[i];if(a[i]==10)c[i]="10" ;else c[i]=int(a[i])+'0';}disorder(a,c);int v=1,u=0;for(i=1;i<=number;i++){v=1;for(j=1;j<i;j++)if(sss[i]==sss[j])v=0;if(v==1){cout<<sss[i]<<endl;u=1;}}if(u==0)cout<<"无解"<<endl;system("pause");return 0;}三,运行结果显示四,调试和运行程序过程中产生的问题及采取的措施:。
24点程序C#代码(随机方法实现)
label1.Content = ra.Next(1, 14);
label2.Content = ra.Next(1, 14);
label3.Content = ra.Next(1, 14);
label4.Content = ra.Next(1, 14);
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
double s3 = s1.ran(result5, result6, math2); //s3为抽两个数随机运算,r7没用
double s4 = s1.ran(s3, result7, math3); //s4为最终结果
label5.Content = "";
}
private void button2_Click(object sender, RoutedEventArgs e)
{
yunsuan s1 = new yunsuan(); //s1为运算对象
do { random1 = ra.Next(0, 4); }
while (random1 ==random );
result2 =array [random1 ];
}
for (int i = 0; i < 100000; i++)
{
int math1 = ra.Next(1, 5); //math1为随机运算符1
数据结构24点游戏源代码
#include<stdio.h>#include<string.h>#include<stdlib.h>#include<time.h>#define OPSETSIZE 7#define STACK_INIF_SIZE 50#define STACKINCREMENT 10int number[2][4];enum{eNumber = 0, //操作数eOperator = 1 //算子};int oper[7]={43,45,42,47,40,41,35};char OPSET[OPSETSIZE]={'+' , '-' , '*' , '/' ,'(' , ')' , '#'};typedef struct sqlist{int bol;//bol 是0 时,num-ch是一个数字;bol 是1 时num_ch 运算符int num_ch;struct sqlist *next;}sqlist;//线性表typedef struct sqstack{int *base;int *top;int stacksize;}sqstack;//栈的定义unsigned char Prior[7][7] = {// 课本表3.1 算符间的优先关系'>','>','<','<','<','>','>','>','>','<','<','<','>','>','>','>','>','>','<','>','>','>','>','>','>','<','>','>','<','<','<','<','<','=',' ','>','>','>','>',' ','>','>','<','<','<','<','<',' ','='};int init_sq(sqlist *l){//初始化链表l=(sqlist*)malloc(sizeof(sqlist));if(l==NULL){exit(-2);}l->next=NULL;return 1;}int insert_sq(sqlist **p,int e,int bl){//链表插入操作sqlist *q;q=(sqlist*)malloc(sizeof(sqlist));q->num_ch=e;q->bol=bl;q->next=NULL;(*p)->next=q;(*p)=(*p)->next;return 1;}int check(sqlist l)//保证输入的数字是给出的四个数字{int right=1,find=0,i;sqlist *q=&l;q=q->next ;for (;q->next!=NULL;q=q->next){if(q->bol==1){if(q->num_ch <=39||q->num_ch>57||q->num_ch==44||q->num_ch==46){ right=0;printf("%c不是有效的运算符!\n");}}else {find=0;for(i=0;i<4;i++){if(number[1][i]==0&&number[0][i]==q->num_ch ){number[1][i]=1;find=1;break;}}if(find==0){printf("%d 不在给出的四个数字中!\n",q->num_ch );right=0;}}}//end forfor (i=0;i<4;i++){if(number[1][i]==0){printf("%d没有用上!\n",number[0][i]);right=0;}}return right;}int chang(char *s,sqlist *l){//将用户的输入转化为单链表int t=0;unsigned int i=0;int bl,ch;int a1,a2,a;sqlist *p=l;for (;i<strlen(s);i++){if(s[i]>47&&s[i]<58&&t==0){a1=(int)s[i]-48;t++;}else if(s[i]>47&&s[i]<58&&t==1){a2=(int)s[i]-48;a=a1*10+a2;t++;}else if(s[i]<48&&s[i]>39&&s[i]!=44&&s[i]!=46){ if(t==1){bl=0;insert_sq(&p,a1,bl);t=0;}else if(t==2){bl=0;insert_sq(&p,a,bl);t=0;}bl=1;ch=(int)s[i];insert_sq(&p,ch,bl);t=0;}else {printf("%c不是有效的运算符!\n",s[i]);}} //end fori=strlen(s)-1;if(s[i]>47&&s[i]<58){if(s[i-1]>47&&s[i-1]<58){bl=0;insert_sq(&p,a,bl);}else {bl=0;insert_sq(&p,a1,bl);}}bl=1;a=35;insert_sq(&p,a,bl);return (check(*l));}int Operate(int a,int theta, int b){//计算switch(theta) {case 43: return a+b;case 45: return a-b;case 42: return a*b;case 47:{if(b==0){return -2000;}if (a%b==0){return a/b;}else {//printf("不能为小数\n");return -10000;}}default : return 0;}}int ReturnOpOrd(char op,char* TestOp)// precede()函数调用求优先级{int i;for(i=0; i< OPSETSIZE; i++){if (op == TestOp[i]) return i;}return 0;}char precede(char Aop, char Bop){return Prior[ReturnOpOrd(Aop,OPSET)][ReturnOpOrd(Bop,OPSET)];}int initstack(sqstack *s){(s)->base = (int*)malloc(STACK_INIF_SIZE*sizeof(int));if((s)->base==NULL) exit(-2);(s)->top=(s)->base;(s)->stacksize = STACK_INIF_SIZE;return 1;}int gettop(sqstack *s){ //取得栈顶元素int e;if(s->top==s->base){printf("栈空,无法取得栈顶元素!\n");return 0;}e=*(s->top-1);return e;}int push(sqstack *s,int e){ //压栈if(s->top-s->base>=s->stacksize){s->base=(int*)realloc(s->base,(s->stacksize+STACKINCREMENT)*sizeof(int));if(!s->base) exit(-2);s->stacksize+= STACKINCREMENT;}*(s->top++)=e;return 1;}int pop(sqstack *s,int *e){ //出栈if(s->top==s->base){printf("栈空,出栈错误!\n");return 0;}*e=*(--s->top);return 1;}int EvaluateExpression(char* MyExpression) { // 算法3.4----计算表达式的值// 算术表达式求值的算符优先算法。
自己编写的算24点c法度模范代码(解答无重复)[整理版]
自己编写的算24点c++程序代码(解答无重复)<删除本句话,并将文件后缀改为.cpp>#include <iostream>using namespace std;const double ANS=24;double sourse[4], suan[4];void four(){ if (suan[0]+suan[1]+suan[2]+suan[3]==ANS) cout<<suan[0]<<"+"<<suan[1]<<"+"<<suan[2]<<"+"<<suan[3]<<"="<<A NS<<endl;if (suan[0]*suan[1]*suan[2]*suan[3]==ANS) cout<<suan[0]<<"*"<<suan[1]<<"*"<<suan[2]<<"*"<<suan[3]<<"="<<A NS<<endl;}void three(){ if (suan[0]+suan[1]+suan[2]-suan[3]==ANS) cout<<suan[0]<<"+"<<suan[1]<<"+"<<suan[2]<<"-"<<suan[3]<<"="<<A NS<<endl;if (suan[0]*suan[1]*suan[2]+suan[3]==ANS) cout<<suan[0]<<"*"<<suan[1]<<"*"<<suan[2]<<"+"<<suan[3]<<"="<<A NS<<endl;if (suan[3]-suan[0]-suan[1]-suan[2]==ANS) cout<<suan[3]<<"-"<<suan[0]<<"-"<<suan[1]<<"-"<<suan[2]<<"="<<A NS<<endl;if (suan[0]*suan[1]*suan[2]-suan[3]==ANS) cout<<suan[0]<<"*"<<suan[1]<<"*"<<suan[2]<<"-"<<suan[3]<<"="<<A NS<<endl;if (suan[3]-suan[0]*suan[1]*suan[2]==ANS) cout<<suan[3]<<"-"<<suan[0]<<"*"<<suan[1]<<"*"<<suan[2]<<"="<<A NS<<endl;if (suan[3]/suan[0]/suan[1]/suan[2]==ANS) cout<<suan[3]<<"/"<<suan[0]<<"/"<<suan[1]<<"/"<<suan[2]<<"="<<A NS<<endl;if (suan[0]*suan[1]*suan[2]/suan[3]==ANS) cout<<suan[0]<<"*"<<suan[1]<<"*"<<suan[2]<<"/"<<suan[3]<<"="<<A NS<<endl;if ((suan[0]+suan[1]+suan[2])*suan[3]==ANS) cout<<"("<<suan[0]<<"+"<<suan[1]<<"+"<<suan[2]<<")*"<<suan[3]<< "="<<ANS<<endl;if ((suan[0]+suan[1]+suan[2])/suan[3]==ANS) cout<<"("<<suan[0]<<"+"<<suan[1]<<"+"<<suan[2]<<")/"<<suan[3]<< "="<<ANS<<endl;if (suan[3]/(suan[0]+suan[1]+suan[2])==ANS) cout<<suan[3]<<"/("<<suan[0]<<"+"<<suan[1]<<"+"<<suan[2]<<")="< <ANS<<endl;}void two(){ if (suan[2]-suan[0]*suan[1]-suan[3]==ANS) cout<<suan[2]<<"-"<<suan[0]<<"*"<<suan[1]<<"-"<<suan[3]<<"="<<A NS<<endl;if (suan[2]/suan[3]+suan[0]+suan[1]==ANS) cout<<suan[2]<<"/"<<suan[3]<<"+"<<suan[0]<<"+"<<suan[1]<<"="<<A NS<<endl;if (suan[2]/suan[0]/suan[1]+suan[3]==ANS) cout<<suan[2]<<"/"<<suan[0]<<"/"<<suan[1]<<"+"<<suan[3]<<"="<<A NS<<endl;if (suan[2]/suan[3]-suan[0]-suan[1]==ANS) cout<<suan[2]<<"/"<<suan[3]<<"-"<<suan[0]<<"-"<<suan[1]<<"="<<ANS<<endl;if (suan[2]/suan[0]/suan[1]-suan[3]==ANS) cout<<suan[2]<<"/"<<suan[0]<<"/"<<suan[1]<<"-"<<suan[3]<<"="<<A NS<<endl;if (suan[2]-suan[3]/suan[0]/suan[1]==ANS) cout<<suan[2]<<"-"<<suan[3]<<"/"<<suan[0]<<"/"<<suan[1]<<"="<<A NS<<endl;if (suan[2]+suan[0]*suan[1]-suan[3]==ANS) cout<<suan[2]<<"+"<<suan[0]<<"*"<<suan[1]<<"-"<<suan[3]<<"="<<A NS<<endl;if (suan[0]+suan[1]-suan[2]/suan[3]==ANS) cout<<suan[0]<<"+"<<suan[1]<<"-"<<suan[2]<<"/"<<suan[3]<<"="<<A NS<<endl;if (suan[0]*suan[1]-suan[2]/suan[3]==ANS) cout<<suan[0]<<"*"<<suan[1]<<"-"<<suan[2]<<"/"<<suan[3]<<"="<<A NS<<endl;if (suan[2]/suan[3]-suan[0]*suan[1]==ANS) cout<<suan[2]<<"/"<<suan[3]<<"-"<<suan[0]<<"*"<<suan[1]<<"="<<A NS<<endl;if (suan[0]*suan[1]/suan[2]-suan[3]==ANS) cout<<suan[0]<<"*"<<suan[1]<<"/"<<suan[2]<<"-"<<suan[3]<<"="<<A NS<<endl;if (suan[2]-suan[0]*suan[1]/suan[3]==ANS) cout<<suan[2]<<"-"<<suan[0]<<"*"<<suan[1]<<"/"<<suan[3]<<"="<<A NS<<endl;if ((suan[0]+suan[1])/suan[2]-suan[3]==ANS) cout<<"("<<suan[0]<<"+"<<suan[1]<<")/"<<suan[2]<<"-"<<suan[3]<< "="<<ANS<<endl;if ((suan[2]-suan[3])/suan[0]/suan[1]==ANS) cout<<"("<<suan[2]<<"-"<<suan[3]<<")/"<<suan[0]<<"/"<<suan[1]<< "="<<ANS<<endl;if (suan[2]+(suan[0]+suan[1])/suan[3]==ANS) cout<<suan[2]<<"+("<<suan[0]<<"+"<<suan[1]<<")/"<<suan[3]<<"="< <ANS<<endl;if (suan[2]-(suan[0]+suan[1])*suan[3]==ANS) cout<<suan[2]<<"-("<<suan[0]<<"+"<<suan[1]<<")*"<<suan[3]<<"="< <ANS<<endl;if (suan[2]-(suan[0]+suan[1])/suan[3]==ANS) cout<<suan[2]<<"-("<<suan[0]<<"+"<<suan[1]<<")/"<<suan[3]<<"="< <ANS<<endl;if (suan[2]*(suan[0]+suan[1])+suan[3]==ANS) cout<<suan[2]<<"*("<<suan[0]<<"+"<<suan[1]<<")+"<<suan[3]<<"="< <ANS<<endl;if (suan[2]/(suan[0]+suan[1])+suan[3]==ANS) cout<<suan[2]<<"/("<<suan[0]<<"+"<<suan[1]<<")+"<<suan[3]<<"="< <ANS<<endl;if (suan[2]*(suan[0]+suan[1])-suan[3]==ANS) cout<<suan[2]<<"*("<<suan[0]<<"+"<<suan[1]<<")-"<<suan[3]<<"="< <ANS<<endl;if (suan[2]/(suan[0]+suan[1])-suan[3]==ANS) cout<<suan[2]<<"/("<<suan[0]<<"+"<<suan[1]<<")-"<<suan[3]<<"="< <ANS<<endl;if (suan[2]*(suan[0]+suan[1])/suan[3]==ANS) cout<<suan[2]<<"*("<<suan[0]<<"+"<<suan[1]<<")/"<<suan[3]<<"="< <ANS<<endl;if (suan[2]/(suan[0]+suan[1])/suan[3]==ANS) cout<<suan[2]<<"/("<<suan[0]<<"+"<<suan[1]<<")/"<<suan[3]<<"="< <ANS<<endl;if (suan[0]/(suan[2]-suan[3])*suan[1]==ANS) cout<<suan[0]<<"/("<<suan[2]<<"-"<<suan[3]<<")*"<<suan[1]<<"="< <ANS<<endl;if (suan[0]*(suan[2]-suan[3])*suan[1]==ANS) cout<<suan[0]<<"*("<<suan[2]<<"-"<<suan[3]<<")*"<<suan[1]<<"="< <ANS<<endl;if ((suan[0]+suan[1]-suan[2])*suan[3]==ANS) cout<<"("<<suan[0]<<"+"<<suan[1]<<"-"<<suan[2]<<")*"<<suan[3]<< "="<<ANS<<endl;if ((suan[2]-suan[0]-suan[1])*suan[3]==ANS) cout<<"("<<suan[2]<<"-"<<suan[0]<<"-"<<suan[1]<<")*"<<suan[3]<< "="<<ANS<<endl;if ((suan[2]+suan[0]*suan[1])*suan[3]==ANS) cout<<"("<<suan[2]<<"+"<<suan[0]<<"*"<<suan[1]<<")*"<<suan[3]<< "="<<ANS<<endl;if ((suan[2]-suan[0]*suan[1])*suan[3]==ANS) cout<<"("<<suan[2]<<"-"<<suan[0]<<"*"<<suan[1]<<")*"<<suan[3]<< "="<<ANS<<endl;if ((suan[0]*suan[1]-suan[2])*suan[3]==ANS) cout<<"("<<suan[0]<<"*"<<suan[1]<<"-"<<suan[2]<<")*"<<suan[3]<< "="<<ANS<<endl;if ((suan[0]+suan[1]-suan[2])/suan[3]==ANS) cout<<"("<<suan[0]<<"+"<<suan[1]<<"-"<<suan[2]<<")/"<<suan[3]<< "="<<ANS<<endl;if ((suan[2]-suan[0]-suan[1])/suan[3]==ANS) cout<<"("<<suan[2]<<"-"<<suan[0]<<"-"<<suan[1]<<")/"<<suan[3]<< "="<<ANS<<endl;if ((suan[2]+suan[0]*suan[1])/suan[3]==ANS) cout<<"("<<suan[2]<<"+"<<suan[0]<<"*"<<suan[1]<<")/"<<suan[3]<< "="<<ANS<<endl;if ((suan[2]-suan[0]*suan[1])/suan[3]==ANS) cout<<"("<<suan[2]<<"-"<<suan[0]<<"*"<<suan[1]<<")/"<<suan[3]<< "="<<ANS<<endl;if ((suan[0]*suan[1]-suan[2])/suan[3]==ANS) cout<<"("<<suan[0]<<"*"<<suan[1]<<"-"<<suan[2]<<")/"<<suan[3]<<"="<<ANS<<endl;if (suan[2]/(suan[0]+suan[1]-suan[3])==ANS) cout<<suan[2]<<"/("<<suan[0]<<"+"<<suan[1]<<"-"<<suan[3]<<")="< <ANS<<endl;if (suan[2]/(suan[3]-suan[0]-suan[1])==ANS) cout<<suan[2]<<"/("<<suan[3]<<"-"<<suan[0]<<"-"<<suan[1]<<")="< <ANS<<endl;if (suan[2]/(suan[3]+suan[0]*suan[1])==ANS) cout<<suan[2]<<"/("<<suan[3]<<"+"<<suan[0]<<"*"<<suan[1]<<")="< <ANS<<endl;if (suan[2]/(suan[3]-suan[0]*suan[1])==ANS) cout<<suan[2]<<"/("<<suan[3]<<"-"<<suan[0]<<"*"<<suan[1]<<")="< <ANS<<endl;if (suan[2]/(suan[0]*suan[1]-suan[3])==ANS) cout<<suan[2]<<"/("<<suan[0]<<"*"<<suan[1]<<"-"<<suan[3]<<")="< <ANS<<endl;if ((suan[0]+suan[1])*(suan[2]-suan[3])==ANS) cout<<"("<<suan[0]<<"+"<<suan[1]<<")*("<<suan[2]<<"-"<<suan[3]< <")="<<ANS<<endl;if ((suan[0]+suan[1])/(suan[2]-suan[3])==ANS) cout<<"("<<suan[0]<<"+"<<suan[1]<<")/("<<suan[2]<<"-"<<suan[3]< <")="<<ANS<<endl;}void dou_two(){ if (suan[0]+suan[1]-suan[2]-suan[3]==ANS) cout<<suan[0]<<"+"<<suan[1]<<"-"<<suan[2]<<"-"<<suan[3]<<"="<<A NS<<endl;if (suan[0]*suan[1]+suan[2]+suan[3]==ANS) cout<<suan[0]<<"*"<<suan[1]<<"+"<<suan[2]<<"+"<<suan[3]<<"="<<A NS<<endl;if (suan[0]*suan[1]-suan[2]-suan[3]==ANS) cout<<suan[0]<<"*"<<suan[1]<<"-"<<suan[2]<<"-"<<suan[3]<<"="<<A NS<<endl;if (suan[0]*suan[1]-suan[2]*suan[3]==ANS) cout<<suan[0]<<"*"<<suan[1]<<"-"<<suan[2]<<"*"<<suan[3]<<"="<<A NS<<endl;if (suan[0]*suan[1]/suan[2]/suan[3]==ANS) cout<<suan[0]<<"*"<<suan[1]<<"/"<<suan[2]<<"/"<<suan[3]<<"="<<A NS<<endl;if (suan[0]+suan[1]-suan[2]*suan[3]==ANS) cout<<suan[0]<<"+"<<suan[1]<<"-"<<suan[2]<<"*"<<suan[3]<<"="<<A NS<<endl;if ((suan[0]+suan[1])/suan[2]/suan[3]==ANS) cout<<"("<<suan[0]<<"+"<<suan[1]<<")/"<<suan[2]<<"/"<<suan[3]<< "="<<ANS<<endl;if (suan[2]/(suan[0]+suan[1])*suan[3]==ANS) cout<<suan[2]<<"/("<<suan[0]<<"+"<<suan[1]<<")*"<<suan[3]<<"="< <ANS<<endl;if (suan[2]*(suan[0]+suan[1])*suan[3]==ANS) cout<<suan[2]<<"*("<<suan[0]<<"+"<<suan[1]<<")*"<<suan[3]<<"="< <ANS<<endl;if ((suan[0]+suan[1])/(suan[2]+suan[3])==ANS) cout<<"("<<suan[0]<<"+"<<suan[1]<<")/("<<suan[2]<<"+"<<suan[3]< <")="<<ANS<<endl;}void exp(){if (suan[0]/suan[1]+suan[2]/suan[3]==ANS) cout<<suan[0]<<"/"<<suan[1]<<"+"<<suan[2]<<"/"<<suan[3]<<"="<<A NS<<endl;}void ext(){if ((suan[0]-suan[1])*(suan[2]-suan[3])==ANS) cout<<"("<<suan[0]<<"-"<<suan[1]<<")*("<<suan[2]<<"-"<<suan[3]< <")="<<ANS<<endl;}void ex2(){if ((suan[0]+suan[1])*(suan[2]+suan[3])==ANS) cout<<"("<<suan[0]<<"+"<<suan[1]<<")*("<<suan[2]<<"+"<<suan[3]< <")="<<ANS<<endl;if (suan[0]*suan[1]+suan[2]*suan[3]==ANS) cout<<suan[0]<<"*"<<suan[1]<<"+"<<suan[2]<<"*"<<suan[3]<<"="<<A NS<<endl;}void one(){ if (suan[0]/suan[1]-suan[2]/suan[3]==ANS) cout<<suan[0]<<"/"<<suan[1]<<"-"<<suan[2]<<"/"<<suan[3]<<"="<<A NS<<endl;if (suan[0]+suan[1]/suan[2]-suan[3]==ANS) cout<<suan[0]<<"+"<<suan[1]<<"/"<<suan[2]<<"-"<<suan[3]<<"="<<A NS<<endl;if ((suan[0]-suan[1])/suan[2]-suan[3]==ANS) cout<<"("<<suan[0]<<"-"<<suan[1]<<")/"<<suan[2]<<"-"<<suan[3]<< "="<<ANS<<endl;if (suan[0]-suan[1]/suan[2]-suan[3]==ANS) cout<<suan[0]<<"-"<<suan[1]<<"/"<<suan[2]<<"-"<<suan[3]<<"="<<ANS<<endl;if (suan[0]+(suan[1]-suan[2])/suan[3]==ANS) cout<<suan[0]<<"+("<<suan[1]<<"-"<<suan[2]<<")/"<<suan[3]<<"="< <ANS<<endl;if (suan[0]*(suan[1]-suan[2])+suan[3]==ANS) cout<<suan[0]<<"*("<<suan[1]<<"-"<<suan[2]<<")+"<<suan[3]<<"="< <ANS<<endl;if (suan[0]/(suan[1]-suan[2])+suan[3]==ANS) cout<<suan[0]<<"/("<<suan[1]<<"-"<<suan[2]<<")+"<<suan[3]<<"="< <ANS<<endl;if (suan[0]*(suan[1]-suan[2])-suan[3]==ANS) cout<<suan[0]<<"*("<<suan[1]<<"-"<<suan[2]<<")-"<<suan[3]<<"="< <ANS<<endl;if (suan[0]/(suan[1]-suan[2])-suan[3]==ANS) cout<<suan[0]<<"/("<<suan[1]<<"-"<<suan[2]<<")-"<<suan[3]<<"="< <ANS<<endl;if (suan[0]*(suan[1]-suan[2])/suan[3]==ANS) cout<<suan[0]<<"*("<<suan[1]<<"-"<<suan[2]<<")/"<<suan[3]<<"="< <ANS<<endl;if (suan[0]/(suan[1]-suan[2])/suan[3]==ANS) cout<<suan[0]<<"/("<<suan[1]<<"-"<<suan[2]<<")/"<<suan[3]<<"="< <ANS<<endl;if ((suan[0]+suan[1]/suan[2])*suan[3]==ANS) cout<<"("<<suan[0]<<"+"<<suan[1]<<"/"<<suan[2]<<")*"<<suan[3]<< "="<<ANS<<endl;if ((suan[0]-suan[1]/suan[2])*suan[3]==ANS) cout<<"("<<suan[0]<<"-"<<suan[1]<<"/"<<suan[2]<<")*"<<suan[3]<< "="<<ANS<<endl;if ((suan[0]/suan[1]-suan[2])*suan[3]==ANS) cout<<"("<<suan[0]<<"/"<<suan[1]<<"-"<<suan[2]<<")*"<<suan[3]<< "="<<ANS<<endl;if ((suan[0]+suan[1]/suan[2])/suan[3]==ANS) cout<<"("<<suan[0]<<"+"<<suan[1]<<"/"<<suan[2]<<")/"<<suan[3]<< "="<<ANS<<endl;if ((suan[0]-suan[1]/suan[2])/suan[3]==ANS) cout<<"("<<suan[0]<<"-"<<suan[1]<<"/"<<suan[2]<<")/"<<suan[3]<< "="<<ANS<<endl;if ((suan[0]/suan[1]-suan[2])/suan[3]==ANS) cout<<"("<<suan[0]<<"/"<<suan[1]<<"-"<<suan[2]<<")/"<<suan[3]<< "="<<ANS<<endl;if (suan[0]/(suan[1]+suan[2]/suan[3])==ANS) cout<<suan[0]<<"/("<<suan[1]<<"+"<<suan[2]<<"/"<<suan[3]<<")="< <ANS<<endl;if (suan[0]/(suan[1]-suan[2]/suan[3])==ANS) cout<<suan[0]<<"/("<<suan[1]<<"-"<<suan[2]<<"/"<<suan[3]<<")="< <ANS<<endl;if (suan[0]/(suan[1]/suan[2]-suan[3])==ANS) cout<<suan[0]<<"/("<<suan[1]<<"/"<<suan[2]<<"-"<<suan[3]<<")="< <ANS<<endl;if ((suan[0]-suan[1])/(suan[2]-suan[3])==ANS &&(suan[0]-suan[1])*(suan[2]-suan[3])!=0) cout<<"("<<suan[0]<<"-"<<suan[1]<<")/("<<suan[2]<<"-"<<suan[3]< <")="<<ANS<<endl;}int main(){ int i=0, j=0, k=0;int count=0;int tong1; int tong2; int tong3; int butong1; int butong2;int bao1; int bao2; int bao3; int zi1; int zi2;bool flag=false;char ch='y';do{count=0;do {cout <<"请输入四个正整数:";cin >>sourse[0]>>sourse[1]>>sourse[2]>>sourse[3];} while (sourse[0]<1 || sourse[1]<1 || sourse[2]<1 || sourse[3]<1);for (i=0; i<3; i++)for (j=i+1; j<4; j++){ if (sourse[i]==sourse[j]){ count++;if (flag) count++;flag=true;}flag=false;}switch (count){ case 0:for (i=0; i<4; i++){suan[0]=sourse[i];for (j=0; j<4; j++)if (j!=i){suan[1]=sourse[j];for (k=0; k<4; k++)if (k!=i && k!=j){suan[2]=sourse[k];suan[3]=sourse[6-i-j-k]; one();}}}for (i=0; i<6; i++){bao1=i%4; bao2=(i+1+i/4)%4; zi1=(i+2+i/4)%4; zi2=6-bao1-bao2-zi1;suan[0]=sourse[bao1]; suan[1]=sourse[bao2]; suan[2]=sourse[zi1]; suan[3]=sourse[zi2];dou_two(); two();suan[2]=sourse[zi2]; suan[3]=sourse[zi1]; two();}for (i=0; i<3; i++){bao1=i; bao2=(i+1)%3; zi1=(i+2)%3;zi2=6-bao1-bao2-zi1;suan[0]=sourse[bao1]; suan[1]=sourse[bao2]; suan[2]=sourse[zi1]; suan[3]=sourse[zi2];ext(); exp(); ex2();suan[2]=sourse[zi2]; suan[3]=sourse[zi1]; ext(); exp();suan[0]=sourse[bao2]; suan[1]=sourse[bao1]; exp();suan[2]=sourse[zi1]; suan[3]=sourse[zi2];exp();}for (i=0; i<4; i++){bao1=i; bao2=(i+1)%4; bao3=(i+2)%4; zi1=(i+3)%4;suan[0]=sourse[bao1]; suan[1]=sourse[bao2]; suan[2]=sourse[bao3]; suan[3]=sourse[zi1];three();}suan[0]=sourse[0]; suan[1]=sourse[1];suan[2]=sourse[2]; suan[3]=sourse[3];four(); break;case 1:for (i=0; i<3; i++){for (j=i+1; j<4; j++)if (sourse[i]==sourse[j]) break;if (sourse[i]==sourse[j]) break;}tong1=i; tong2=j;for (i=0; i<4; i++)if (i!=tong1 && i!=tong2){butong1=i; butong2=6-tong1-tong2-butong1; break;}suan[0]=sourse[tong1]; suan[1]=sourse[tong2]; suan[2]=sourse[butong1]; suan[3]=sourse[butong2];four(); two(); dou_two(); three(); ext(); exp(); ex2(); one();suan[2]=sourse[butong2]; suan[3]=sourse[butong1]; two(); three(); ext(); exp(); one();suan[0]=sourse[butong1]; suan[1]=sourse[tong1]; suan[2]=sourse[tong2]; suan[3]=sourse[butong2];two(); dou_two(); ext(); exp(); ex2(); one();suan[0]=sourse[butong2]; suan[3]=sourse[butong1]; two(); dou_two(); exp(); one();suan[0]=sourse[butong1]; suan[1]=sourse[butong2]; suan[2]=sourse[tong1]; suan[3]=sourse[tong2];two(); dou_two(); three(); one();suan[0]=sourse[butong2]; suan[1]=sourse[butong1]; one();suan[0]=sourse[tong1]; suan[1]=sourse[butong1]; suan[2]=sourse[butong2]; suan[3]=sourse[tong2];two(); one();suan[1]=sourse[butong2]; suan[2]=sourse[butong1]; two(); one();suan[0]=sourse[tong1]; suan[1]=sourse[butong1]; suan[2]=sourse[tong2]; suan[3]=sourse[butong2];ext(); exp(); one();suan[1]=sourse[butong2]; suan[3]=sourse[butong1]; one();suan[0]=sourse[butong1]; suan[1]=sourse[tong1]; suan[2]=sourse[butong2]; suan[3]=sourse[tong2];exp(); one();suan[0]=sourse[butong2]; suan[2]=sourse[butong1]; one(); break;case 2:for (i=1; i<4; i++)if (sourse[i]==sourse[0]) break;tong1=0; tong2=i;for (i=0; i<4; i++)if (i!=tong1 && i!=tong2){butong1=i; butong2=6-tong1-tong2-butong1; break;}suan[0]=sourse[tong1]; suan[1]=sourse[tong2]; suan[2]=sourse[butong1]; suan[3]=sourse[butong2];four(); two(); dou_two(); ext(); exp(); ex2(); three(); one();suan[0]=sourse[butong1]; suan[1]=sourse[tong1]; suan[2]=sourse[tong2]; suan[3]=sourse[butong2];two(); dou_two(); ext(); exp(); ex2(); one();suan[0]=sourse[butong1]; suan[1]=sourse[butong2]; suan[2]=sourse[tong1]; suan[3]=sourse[tong2];two(); dou_two(); three(); one();suan[0]=sourse[tong1]; suan[1]=sourse[butong1]; suan[2]=sourse[butong2]; suan[3]=sourse[tong2];two(); one();suan[0]=sourse[tong1]; suan[1]=sourse[butong1]; suan[2]=sourse[tong2]; suan[3]=sourse[butong2];ext(); exp(); one();suan[0]=sourse[butong1]; suan[1]=sourse[tong1]; suan[2]=sourse[butong2]; suan[3]=sourse[tong2];exp(); one(); break;case 3:for (i=0; i<4; i++)if(sourse[i]!=sourse[(i+1)%4] &&sourse[i]!=sourse[(i+2)%4]) break;butong1=i; tong1=3-i;for (i=0; i<4; i++)if (i!=butong1 && i!=tong1){tong2=i; tong3=6-tong1-tong2-butong1; break;}suan[0]=sourse[tong1]; suan[1]=sourse[tong2]; suan[2]=sourse[tong3]; suan[3]=sourse[butong1];four(); two(); dou_two(); three(); ext(); exp(); ex2(); one();suan[0]=sourse[tong1]; suan[1]=sourse[tong2]; suan[2]=sourse[butong1]; suan[3]=sourse[tong3];two(); three(); exp(); one();suan[0]=sourse[tong1]; suan[1]=sourse[butong1]; suan[2]=sourse[tong2]; suan[3]=sourse[tong3];two(); dou_two(); one();suan[0]=sourse[butong1]; suan[1]=sourse[tong1]; suan[2]=sourse[tong2]; suan[3]=sourse[tong3];one(); break;case 6:suan[0]=sourse[0]; suan[1]=sourse[1];suan[2]=sourse[2]; suan[3]=sourse[3];four(); two(); dou_two(); three(); ext(); exp(); one();break;}do{cout << "继续?(y/n):"; cin >> ch;} while (ch!='y' && ch!='n' && ch!='Y' && ch!='N');} while (ch=='y' || ch=='Y');return 0;}。
24点游戏源代码
else if(tempp[i] == 60003)
u = u * v;
else if(tempp[i] == 60004)
u = v / u;
tempp[i] = u;
}
}
ssum = u;
}
int checkk(void)
float a[4];
float bb[4];
float ssum;
char temp;
char output[MAX] ;
char stack[MAX] ;
char input[MAX] ;
char *s, *t ; /*pointers to input and output strings*/
float sum(float xx,float yy,char mm);
void test24(float x[],char m[]);
int main(){
float sum(float,float,char);
void test24(float [],char []);
{
if(tempp[j] <=60000)
{
v=tempp[j];
tempp[j] = 60010;
break; Biblioteka } j--; }
if(tempp[i] == 60001)
u = u + v;
else if(tempp[i] == 60002)
}
ssum = 0.0;
SetExpression (input) ;
ConvertToPostfix ( ) ;
C语言计算24点(原创完美版)
#include<stdio.h>char cha[4]="+-*/",c=0;float fun(float a1,float a2,int b){switch(b) //选择四则运算{case 0:return (a1+a2);case 1:return (a1-a2);case 2:return (a1*a2);case 3:return (a1/a2);}}void algebra(int x[4])//计算满足要求的表达式{int i,j,k;float temp1,temp2,temp3;for(i=0;i<4;i++)for(j=0;j<4;j++)for(k=0;k<4;k++){temp1=fun(x[0],x[1],i);temp2=fun(temp1,x[2],j);temp3=fun(temp2,x[3],k);if(temp3==24){printf("\t\t\t\t[(%d%c%d)%c%d]%c%d=24\n",x[0],cha[i],x[1],cha[j],x[2],cha [k],x[3]);c=1;}temp1=fun(x[0],x[1],i);temp2=fun(x[2],x[3],k);temp3=fun(temp1,temp2,j);if(temp3==24){printf("\t\t\t\t(%d%c%d)%c(%d%c%d)=24\n",x[0],cha[i],x[1],cha[j],x[2],cha [k],x[3]);c=1;}temp1=fun(x[1],x[2],j);temp2=fun(temp1,x[0],i);temp3=fun(temp2,x[3],k);if(temp3==24){printf("\t\t\t\t[%d%c(%d%c%d)]%c%d=24\n",x[0],cha[i],x[1],cha[j],x[2],cha [k],x[3]);c=1;}temp1=fun(x[1],x[2],j);temp2=fun(temp1,x[3],k);temp3=fun(temp2,x[0],i);if(temp3==24){printf("\t\t\t\t%d%c[(%d%c%d)%c%d]=24\n",x[0],cha[i],x[1],cha[j],x[2],cha [k],x[3]);c=1;}temp1=fun(x[2],x[3],k);temp2=fun(temp1,x[1],j);temp3=fun(temp2,x[0],i);if(temp3==24){printf("\t\t\t\t%d%c[%d%c(%d%c%d)]=24\n",x[0],cha[i],x[1],cha[j],x[2],cha [k],x[3]);c=1;}}}int arrange(int num[4])//将四个数排列为24种方式{int i,j,k,l;int temp[4];for(i=0;i<4;i++)for(j=0;j<4;j++)for(k=0;k<4;k++)for(l=0;l<4;l++){if(i!=j&&i!=k&&i!=l&&j!=k&&j!=l&&k!=l){temp[0]=num [i];temp[1]=num[j];temp[2]=num[k];temp[3]=num[l];algebra(temp);}}}int main(){int i, num[4];char ch;printf(" **计算24点游戏**\n\n请输入4个整数,然后按“回车”键: \n");for(i=0;i<4;i++)scanf("%d",&num[i]);//将四个数输入到数组中去printf("结果是:\n");arrange(num);if(c==0)printf("无解.\n");printf("是否继续?(y,n): ");fflush(stdin);ch=getchar();fflush(stdin);if(ch=='n'){printf("\t\t\t\t ****再见!****\n\n");return 0;}while(ch!='y'){printf("输入错误,请重输(y或n): ");ch=getchar();fflush(stdin);if(ch=='n')return 0;}while(ch=='y'){printf("请输入四个整数:");for(i=0;i<4;i++)scanf("%d",&num[i]);//将四个数输入到数组中去fflush(stdin);printf("结果是:\n");arrange(num);if(c==0)printf("无解.\n");printf("是否继续?(y,n): ");ch=getchar();fflush(stdin);if(ch=='n'){printf("\t\t\t\t ******再见!****\n\n");return 0;}while(ch!='y'){printf("输入错误,请重输(y或n): ");ch=getchar();fflush(stdin);if(ch=='n'){printf("\t\t\t\t ******再见!****\n\n");return 0;} }}return 0;}。
24点游戏(C#)
24点游戏(C#)游戏描述:输入参数:4个0…9之间的数字(顺序可调)计算方法:加减乘除(括号)计算结果:24程序截图:程序描述:程序的三种模式:1,全部组合(有解):将有解的组合全部列出(因为数据组合较多,一屏可能显示不下,所以分段显示)。
如下图(第一段):2,全部组合(无解含):将所有的组合一一列出,包括无解的组合(同模式一,分屏显示)。
如下图(第一段):3,手动输入(默认):手动输入4个数字,程序自动计算,得出结果。
如下图:程序代码用VS创建ConsoleApplication程序,拷贝一下代码覆盖原代码即可。
(有任何问题,可以私密我)using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;namespace Game24{public class Program{///<summary>///計算結果String///</summary>private static Stack<string> stackResult = new Stack<string>();///<summary>///起動方法///</summary>///<param name="args"></param>public static void Main(string[] args){bool reFlg = true;int[] aryInput = new int[4];Console.ForegroundColor = ConsoleColor.Yellow;Console.WriteLine("===================24点Game===================");Console.WriteLine("========================================tpj");while (reFlg){Console.ForegroundColor = ConsoleColor.Yellow;Console.WriteLine(" 1:全部組合(有解)");Console.WriteLine(" 2:全部組合(無解含)");Console.WriteLine(" 3:手動輸入(默認)");Console.WriteLine(" 4:中止");Console.Write("選択:");string select = Console.ReadLine();#region全部組合if (select == "1" || select == "2"){int mukaisu = 0;int youkaisu = 0;int current = 0;for (int i = 0; i < 10; i++){for (int j = i; j < 10; j++){for (int k = j; k < 10; k++){for (int d = k; d < 10; d++){current++;aryInput[0] = i;aryInput[1] = j;aryInput[2] = k;aryInput[3] = d;bool isRight = Keisan(aryInput);if (select == "1"){if (isRight){youkaisu++;Console.ForegroundColor = ConsoleColor.Gray;Console.Write(string.Format("{0}:{1}、{2}、{3}、{4} ", youkaisu, aryInput[0], aryInput[1], aryInput[2], aryInput[3]));Console.ForegroundColor = ConsoleColor.DarkYellow;string allResult =GetAllResult(stackResult.ToList());Console.WriteLine(allResult);}else{mukaisu++;}}else{if (isRight){youkaisu++;Console.ForegroundColor = ConsoleColor.Gray;Console.Write(string.Format("{0}:{1}、{2}、{3}、{4} ", youkaisu + mukaisu, aryInput[0], aryInput[1], aryInput[2], aryInput[3]));Console.ForegroundColor = ConsoleColor.DarkYellow;string allResult =GetAllResult(stackResult.ToList());Console.WriteLine(allResult);}else{mukaisu++;Console.ForegroundColor = ConsoleColor.Gray;Console.Write(string.Format("{0}:{1}、{2}、{3}、{4} ", youkaisu + mukaisu, aryInput[0], aryInput[1], aryInput[2], aryInput[3]));Console.ForegroundColor = ConsoleColor.DarkYellow;Console.WriteLine("無解...");}}if (current != 0 && current % 120 == 0){Console.ForegroundColor = ConsoleColor.Yellow;Console.Write(string.Format("({0},{1},{2},{3})⇒({4},{5},{6},{7})完了。
c#24点源代码
using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO;using System.Collections;namespace _24Point{public partial class Form1 : Form{private int A, B, C, D;private int NumberA, NumberB, NumberC, NumberD;private int topCard;// 下载于#region 关于一副牌的生成private card[] Deck; //一副牌struct card{public int face; //牌面大小public int suit; //牌面花色public int count; //牌面点数public bool faceup;//牌面是否向上}private void GetDeck() //生成一副牌{Deck = new card[53];int i;int j;for (i = 0; i < 13; i++){for (j = 1; j <= 4; j++){Deck[j + i * 4].face = i + 1;Deck[j + i * 4].suit = j;if (i < 10){Deck[j + i * 4].count = i + 1;}else{Deck[j + i * 4].count = 10;}Deck[j + i * 4].faceup = false;}}}private void Shuffle() //洗牌{Random random = new Random((int)DateTime.Now.Ticks);card middleCard;int j, k;for (int i = 0; i < 1000; i++){j = (int)random.Next(1, 52);k = (int)random.Next(1, 52);middleCard = Deck[j];Deck[j] = Deck[k];Deck[k] = middleCard;}}private void btnStart_Click(object sender, EventArgs e) //开始游戏的时候发四张牌{lblInput.Text = "";GetDeck();Shuffle();topCard = 0;int imageNum;string path;//画第一张牌topCard = topCard = 1;pictureBox1.Visible = true;imageNum = Deck[topCard].suit + (Deck[topCard].face - 1) * 4;path = Directory.GetCurrentDirectory() + @"\images\" + imageNum.ToString() + ".bmp";pictureBox1.Image = Image.FromFile(path);NumberA = Convert.ToInt32(Deck[topCard].face);btnNumber1.Text = NumberA.ToString();//画第二张牌topCard = topCard + 1;pictureBox2.Visible = true;imageNum = Deck[topCard].suit + (Deck[topCard].face - 1) * 4;path = Directory.GetCurrentDirectory() + @"\images\" + imageNum.ToString() + ".bmp";pictureBox2.Image = Image.FromFile(path);NumberB = Convert.ToInt32(Deck[topCard].face);btnNumber2.Text = NumberB.ToString();//画第三张牌topCard = topCard + 1;pictureBox3.Visible = true;imageNum = Deck[topCard].suit + (Deck[topCard].face - 1) * 4;path = Directory.GetCurrentDirectory() + @"\images\" + imageNum.ToString() + ".bmp";pictureBox3.Image = Image.FromFile(path);NumberC = Convert.ToInt32(Deck[topCard].face);btnNumber3.Text = NumberC.ToString();//画第四张牌topCard = topCard + 1;pictureBox4.Visible = true;imageNum = Deck[topCard].suit + (Deck[topCard].face - 1) * 4;path = Directory.GetCurrentDirectory() + @"\images\" + imageNum.ToString() + ".bmp";pictureBox4.Image = Image.FromFile(path);NumberD = Convert.ToInt32(Deck[topCard].face);btnNumber4.Text = NumberD.ToString();btnStart.Visible = false;groupBox1.Visible = true;lblAnswer.Visible = true;}#endregionpublic Form1(){InitializeComponent();Initial();}private void Initial(){pictureBox1.Visible = false;pictureBox2.Visible = false;pictureBox3.Visible = false;pictureBox4.Visible = false;groupBox1.Visible = false;lblAnswer.Visible = false;lblResult.Visible = false;}private void Form1_Load(object sender, EventArgs e){}private void btnNext_Click(object sender, EventArgs e){btnAdd.Enabled = true;btnMinus.Enabled = true;btnDivide.Enabled = true;btnMulti.Enabled = true;btnNumber1.Enabled = true;btnNumber2.Enabled = true;btnNumber3.Enabled = true;btnNumber4.Enabled = true;btnDelete.Enabled = true;btnClear.Enabled = true;btnLeft.Enabled = true;btnRight.Enabled = true;btnEnter.Enabled = true;lblInput.Text = "";lblAnswer.Text = "答案";lblResult.Visible = false;int imageNum;string path;//画第一张牌if (topCard >= 52){topCard = 0;Shuffle();}topCard = topCard + 1;imageNum = Deck[topCard].suit + (Deck[topCard].face - 1) * 4;path = Directory.GetCurrentDirectory() + @"\images\" + imageNum.ToString() + ".bmp";pictureBox1.Image = Image.FromFile(path);NumberA = Convert.ToInt32(Deck[topCard].face);btnNumber1.Text = NumberA.ToString();//画第二张牌if (topCard >= 52){topCard = 0;}topCard = topCard + 1;imageNum = Deck[topCard].suit + (Deck[topCard].face - 1) * 4;path = Directory.GetCurrentDirectory() + @"\images\" + imageNum.ToString() + ".bmp";pictureBox2.Image = Image.FromFile(path);NumberB = Convert.ToInt32(Deck[topCard].face);btnNumber2.Text = NumberB.ToString();//画第三张牌if (topCard >= 52){topCard = 0;Shuffle();}topCard = topCard + 1;imageNum = Deck[topCard].suit + (Deck[topCard].face - 1) * 4;path = Directory.GetCurrentDirectory() + @"\images\" + imageNum.ToString() + ".bmp";pictureBox3.Image = Image.FromFile(path);NumberC = Convert.ToInt32(Deck[topCard].face);btnNumber3.Text = NumberC.ToString();//画第四张牌if (topCard >= 52){topCard = 0;Shuffle();}topCard = topCard + 1;imageNum = Deck[topCard].suit + (Deck[topCard].face - 1) * 4;path = Directory.GetCurrentDirectory() + @"\images\" + imageNum.ToString() + ".bmp";pictureBox4.Image = Image.FromFile(path);NumberD = Convert.ToInt32(Deck[topCard].face);btnNumber4.Text = NumberD.ToString();}public void ChangeLoc24(int i){//24种转换switch (i){case 1:A = NumberA;B = NumberB;C = NumberC;D = NumberD;case 2:A = NumberA;B = NumberB; D = NumberC;C = NumberD;break;case 3:A = NumberA; C = NumberB;B = NumberC; D = NumberD;break;case 4:A = NumberA; C = NumberB; D = NumberC;B = NumberD;break;case 5:A = NumberA; D = NumberB;B = NumberC;C = NumberD;break;case 6:A = NumberA; D = NumberB; C = NumberC;B = NumberD;break;case 7:B = NumberA; A = NumberB;C = NumberC;D = NumberD;break;case 8:B = NumberA; A = NumberB; D = NumberC;C = NumberD;break;case 9:B = NumberA;C = NumberB; A = NumberC;D = NumberD;break;case 10:B = NumberA;C = NumberB;D = NumberC; A = NumberD;break;case 11:B = NumberA; D = NumberB; A = NumberC;C = NumberD;break;case 12:B = NumberA; D = NumberB;C = NumberC; A = NumberD;break;case 13:C = NumberA; A = NumberB; B = NumberC;D = NumberD;break;case 14:C = NumberA; A = NumberB;D = NumberC; B = NumberD;break;case 15:C = NumberA; B = NumberB; A = NumberC;D = NumberD;break;C = NumberA; B = NumberB;D = NumberC; A = NumberD;break;case 17:C = NumberA;D = NumberB; A = NumberC; B = NumberD;break;case 18:C = NumberA;D = NumberB; B = NumberC; A = NumberD;break;case 19:D = NumberA; A = NumberB; B = NumberC; C = NumberD;break;case 20:D = NumberA; A = NumberB; C = NumberC; B = NumberD;break;case 21:D = NumberA; B = NumberB; A = NumberC; C = NumberD;break;case 22:D = NumberA; B = NumberB; C = NumberC; A = NumberD;break;case 23:D = NumberA; C = NumberB; A = NumberC; B = NumberD;break;case 24:D = NumberA; C = NumberB; B = NumberC; A = NumberD;break;}}private void btnAnswer_Click(object sender, EventArgs e){btnAdd.Enabled = false;btnMinus.Enabled = false;btnDivide.Enabled = false;btnMulti.Enabled = false;btnNumber1.Enabled = false;btnNumber2.Enabled = false;btnNumber3.Enabled = false;btnNumber4.Enabled = false;btnDelete.Enabled = false;btnClear.Enabled = false;btnLeft.Enabled = false;btnRight.Enabled = false;btnEnter.Enabled = false;lblAnswer.Text = "答案";#region 24种情况的遍历for (int i = 1; i <= 24; i++){ChangeLoc24(i);ArrayList first =new ArrayList();ArrayList firstStr=new ArrayList();first.Add(A.ToString());firstStr.Add("A");cal(ref first, ref firstStr, B,'B');cal(ref first, ref firstStr, C,'C');cal(ref first, ref firstStr, D,'D');for (int j = 0; j < first.Count; j++){if (Convert.ToInt32(Convert.ToDouble(first[j].ToString())) == 24){firstStr[j] = replaceString(firstStr[j].ToString(), 'A', A);firstStr[j] = replaceString(firstStr[j].ToString(), 'B', B);firstStr[j] = replaceString(firstStr[j].ToString(), 'C', C);firstStr[j] = replaceString(firstStr[j].ToString(), 'D', D);lblAnswer.Text = "答案:" + firstStr[j].ToString() + "=24;";return;}}}#endregionif (lblAnswer.Text == "答案"){lblAnswer.Text = "此题无解";}}private string replaceString(string str, char myChar, int num){int loc=str.IndexOf(myChar);string first = str.Substring(0, loc);str = first + Convert.ToInt16(num) + str.Substring(loc + 1);return str;}private void cal(ref ArrayList num,ref ArrayList numStr, int num2,char myChar){ArrayList newNum = new ArrayList();ArrayList newNumStr = new ArrayList();int temp;for (int i = 0; i < num.Count; i++){int num1 = Convert.ToInt32(num[i].ToString());//加法的情况temp = num1 + num2;newNum.Add(temp.ToString());newNumStr.Add(numStr[i].ToString() + "+" + myChar);//减法的情况if (num1 > num2){temp = num1 - num2;newNum.Add(temp.ToString());newNumStr.Add(numStr[i].ToString() + "-" + myChar);}else{temp = num2 - num1;newNum.Add(temp.ToString());if (numStr[i].ToString().IndexOf('+') != -1 || numStr[i].ToString().IndexOf('-')!=-1){newNumStr.Add(myChar + "-" + "(" + numStr[i].ToString() + ")");}elsenewNumStr.Add(myChar + "-" + numStr[i].ToString());}temp = num1 * num2;newNum.Add(temp.ToString());if (numStr[i].ToString().IndexOf("+") == -1 && numStr[i].ToString().IndexOf("-") == -1){newNumStr.Add(numStr[i].ToString() + "*" + myChar);}else{newNumStr.Add("(" + numStr[i].ToString() + ")" + "*" + myChar);}#region 除法的情况if (num1 > num2){if (num2 != 0 && num1 % num2 == 0){temp = num1 / num2;newNum.Add(temp.ToString());if (numStr[i].ToString().IndexOf("+") == -1 && numStr[i].ToString().IndexOf("-") == -1){newNumStr.Add(numStr[i].ToString() + "/" + myChar);}else{newNumStr.Add("(" + numStr[i].ToString() + ")" + "/" + myChar);}}}else{if (num1 != 0 && num2 % num1 == 0){temp = num2 / num1;newNum.Add(temp.ToString());if (numStr[i].ToString().IndexOf("+") == -1 && numStr[i].ToString().IndexOf("-") == -1){newNumStr.Add(myChar + "/" + numStr[i].ToString());}else{newNumStr.Add(myChar + "/" + "(" + numStr[i].ToString() + ")");}}}#endregion}num = newNum;numStr = newNumStr;}private void btnEnter_Click(object sender, EventArgs e){if (CheckForNumbers(lblInput.Text.ToString().Trim())){int result=Deal(lblInput.Text.ToString().Trim());lblResult.Visible = true;if (result == 24){lblResult.Text = "<<---恭喜您,答对了!--->>";}else{lblResult.Text = "<<--抱歉,您的回答有误!-->>";}}}private void btnNumber1_Click(object sender, EventArgs e){lblInput.Text = lblInput.Text + btnNumber1.Text.ToString().Trim(); }private void btnNumber2_Click(object sender, EventArgs e){lblInput.Text = lblInput.Text + btnNumber2.Text.ToString().Trim(); }private void btnNumber3_Click(object sender, EventArgs e){lblInput.Text = lblInput.Text + btnNumber3.Text.ToString().Trim(); }private void btnNumber4_Click(object sender, EventArgs e){lblInput.Text = lblInput.Text + btnNumber4.Text.ToString().Trim(); }private void btnAdd_Click(object sender, EventArgs e){lblInput.Text = lblInput.Text + btnAdd.Text.ToString().Trim();}private void btnMinus_Click(object sender, EventArgs e){lblInput.Text = lblInput.Text + btnMinus.Text.ToString().Trim();}private void btnMulti_Click(object sender, EventArgs e){lblInput.Text = lblInput.Text + btnMulti.Text.ToString().Trim();}private void btnDivide_Click(object sender, EventArgs e){lblInput.Text = lblInput.Text + btnDivide.Text.ToString().Trim();}private void btnLeft_Click(object sender, EventArgs e){lblInput.Text = lblInput.Text + btnLeft.Text.ToString().Trim();}private void btnRight_Click(object sender, EventArgs e){lblInput.Text = lblInput.Text + btnRight.Text.ToString().Trim();}private void btnDelete_Click(object sender, EventArgs e){string input = lblInput.Text.ToString().Trim();lblInput.Text = input.Substring(0, input.Length - 1);}private void btnClear_Click(object sender, EventArgs e){lblInput.Text = "";}public int Deal(string input)//处理谓词表达式中的括号{int result = 0;while (input.IndexOf(')') != -1){int rightLoc = input.IndexOf(')');string temp = input.Substring(0, rightLoc);int leftLoc = stIndexOf('(');string first = input.Substring(0, leftLoc);string middle = input.Substring(leftLoc + 1, rightLoc - leftLoc - 1);string last = input.Substring(rightLoc + 1);input = first + Formular(middle).ToString() + last;}result = Formular(input);return result;}protected int Formular(string Inputs)//最简式运算{int Len = Inputs.Length;ArrayList OpeLoc = new ArrayList();//记录操作符位置ArrayList Ope = new ArrayList();//记录操作符int i;for (i = 0; i < Len; i++){if (IsOperator(Inputs[i]))//获取算符组信息{OpeLoc.Add(i);Ope.Add(Inputs[i]);}}if (OpeLoc.Count == 0) return int.Parse(Inputs);//处理无算符的情况RebuildOperator(ref OpeLoc, ref Ope);//算符重组,区分负号和减号if (!CheckFunction(OpeLoc, Len)) return 0;//判断算符组是否合法ArrayList Val = new ArrayList();//记录数值内容int j = 0;for (i = 0; i < OpeLoc.Count; i++){V al.Add(int.Parse(Inputs.Substring(j, Convert.ToInt32(OpeLoc[i]) - j)));j = Convert.ToInt32(OpeLoc[i]) + 1;}Val.Add(int.Parse(Inputs.Substring(j, Len - j)));//处理最后一个数据的录入return Calculate(Ope, Val);}protected bool IsOperator(char chr)//判断一个符号是否是基本算符{if (chr == '+' | chr == '-' | chr == '*' | chr == '/')return true;//判断是否是四则混合运算算符else return false;}protected void RebuildOperator(ref ArrayList OpeLoc, ref ArrayList Ope)//对负号的处理和重构{ArrayList DelItem = new ArrayList();if (Convert.ToInt32(OpeLoc[0].ToString()) == 0 & Convert.ToChar(Ope[0]) == '-')//判断第一个符号是否是负号{DelItem.Add(0);}int i;for (i = 1; i < OpeLoc.Count; i++){//判断是否有相邻的算符且后一个是负号if (Convert.ToChar(Ope[i]) == '-' && Convert.ToChar(Ope[i - 1]) != '-' && (Convert.ToInt32(OpeLoc[i]) - Convert.ToInt32(OpeLoc[i - 1])) == 1){DelItem.Add(i);}}for (i = DelItem.Count - 1; i >= 0; i--)//将负号和减号分开处理{Ope.RemoveAt(Convert.ToInt32(DelItem[i]));OpeLoc.RemoveAt(Convert.ToInt32(DelItem[i]));}}protected int Calculate(ArrayList Ope, ArrayList Values)//处理四则混合运算等基础运算{int i;for (i = 0; i < Ope.Count; i++)//处理乘法、除法{switch (Convert.ToChar(Ope[i])){case '*':Values[i] = Convert.ToInt32(Values[i]) * Convert.ToInt32(Values[i+1]);Values.RemoveAt(i + 1);Ope.RemoveAt(i);i--;break;case '/':Values[i] = Convert.ToInt32(Values[i]) / Convert.ToInt32(Values[i + 1]);Values.RemoveAt(i + 1);Ope.RemoveAt(i);i--;break;}}for (i = 0; i < Ope.Count; i++)//处理加法和减法{switch ((char)Ope[i]){case '+':Values[i] = Convert.ToInt32(Values[i]) + Convert.ToInt32(Values[i + 1]);Values.RemoveAt(i + 1);Ope.RemoveAt(i);i--;break;case '-':Values[i] = Convert.ToInt32(Values[i]) - Convert.ToInt32(Values[i+1]);;Values.RemoveAt(i + 1);Ope.RemoveAt(i);i--;break;}}return Convert.ToInt32(Values[0].ToString());}protected bool CheckFunction(ArrayList Loc, int Len)//判断算符组是否合法{if (Convert.ToInt32(Loc[0]) == 0)return false;int i;for (i = 1; i < Loc.Count; i++){if (Convert.ToInt32(Loc[i]) - Convert.ToInt32(Loc[i - 1]) == 1)return false;}if (Convert.ToInt32(Loc[Loc.Count - 1]) == Len - 1)return false;return true;}protected bool CheckForNumbers(string input){bool result = true;string[] str = input.Split(new char[] { '+', '-', '/', '*', '(', ')' }, StringSplitOptions.RemoveEmptyEntries);if (str.Length != 4){MessageBox.Show("抱歉,输入有误!请重新输入");result = false;return result;}int[] numbers=new int[4];int[] nums = { NumberA,NumberB, NumberC, NumberD };Array.Sort(nums);for (int i = 0; i < 4; i++){numbers[i] = Convert.ToInt32(str[i]);}Array.Sort(numbers);for (int i = 0; i < 4; i++){if (nums[i] != numbers[i]){result = false;MessageBox.Show("抱歉,每张牌只能使用一次!");return result;}}return result;}}}。
24点C语言程序
24点C语言程序(基于300平台)【程序流程图】【程序源代码】int radom10(){cc24=0;for(i=0;i<=3;i++){Get_Rtc(&pstrctTime);j=rand()%123;rad = (int)pstrctTime.second^j;um[i] = rad%10;Uart_Printf("%d\n",um[i]);}Cal_242();if(cc24!=1)radom10();elsereturn um[i];}int radom11(){ cc24=0;for(i=0;i<=3;i++){Get_Rtc(&pstrctTime);j=rand()%123;rad = (int)pstrctTime.second^j;um[i] = rad%11;Uart_Printf("%d\n",um[i]);}Cal_242();if(cc24!=1)radom11();elsereturn um[i];}int radom12(){cc24=0;for(i=0;i<=3;i++){Get_Rtc(&pstrctTime);j=rand()%123;rad = (int)pstrctTime.second^j;um[i] = rad%12;Uart_Printf("%d\n",um[i]);}Cal_242();if(cc24!=1)radom12();elsereturn um[i];}int radom13(){cc24=0;for(i=0;i<=3;i++){Get_Rtc(&pstrctTime);j=rand()%123;rad = (int)pstrctTime.second^j;um[i] = rad%13;Uart_Printf("%d\n",um[i]);}Cal_242();if(cc24!=1)radom13();elsereturn um[i];}/*********************************表达式算法***************************************/void SetOutput(){Uart_Printf("\nlength = %i\n",l);output[l] = '\0';}void Initialize (void){top = -1 ;/*Make stack empty*/strcpy ( output, "" ) ;strcpy ( stack, "" ) ;l = 0 ;}/* */void SetExpression ( char *str ){s = str ;l = strlen ( s ) ;t = output;}/* adds operator to the stack */void PushOnStack ( char c ){if ( top == MAX - 1 )printf ( "\nStack is full.\n" ) ;else{top++ ;stack[top] = c ;}}/* pops an operator from the stack */char PopFromStack (void ){if ( top == -1 ) /* Stack is empty*/return -1 ;else{char item = stack[top] ;top-- ;return item ;}}/* returns the priotity of the operator */int priority ( char c ){if ( c == '^' ) return 3 ;/*Exponential operator*/if ( c == '*' || c == '/' || c == '%' ) return 2 ;else if ( c == '+' || c == '-' ) return 1 ;else return 0 ;}/* converts the infix expr. to postfix form */void ConvertToPostfix (void){char opr ;while ( *( s ) ){ /*Skip white spaces, if any*/OSTimeDly(2000);if ( *( s ) == ' ' || *( s ) == '\t' ){s++ ;Uart_Printf("there is a space!");continue ;}Uart_Printf("s3=%s",s);//if ( isdigit ( *( s ) ) || isalpha ( *( s ) ) ) /*Operands*/if ( *( s ) == '1' || *( s ) == '2' || *( s ) == '3' || *( s ) == '4' || *( s ) == '5' || *( s ) == '6' || *( s ) == '7'|| *( s ) == '8'|| *( s ) == '9'|| *( s ) == '0'){while ( *( s ) == '1' || *( s ) == '2' || *( s ) == '3' || *( s ) == '4' || *( s ) == '5' || *( s ) == '6' || *( s ) == '7'|| *( s ) == '8'|| *( s ) == '9'|| *( s ) == '0' ){*( t ) = *( s ) ;Uart_Printf("It's a digital %s %s",s,t);s++;t++;}}if ( *( s ) == '(' )/*Opening Parenthesis*/{l --;PushOnStack ( *( s ) ) ;s++ ;}if ( *( s ) == '*' || *( s ) == '+' || *( s ) == '/' || *( s ) == '%' || *( s ) == '-' || *( s ) == '^' ){if ( top != -1 ){opr = PopFromStack ( ) ;while ( priority ( opr ) >=priority ( *( s ) ) ){*( t ) = opr ;t++ ;opr =PopFromStack ( ) ;}PushOnStack ( opr ) ;PushOnStack ( *( s ) ) ;}else PushOnStack ( *( s ) ) ;Uart_Printf("It's a operator %s",s);s++ ;}if ( *( s ) == ')' )/*Closing Parenthesis*/{l --;opr = PopFromStack ( ) ;while ( opr != '(' ){*( t ) = opr ;t++ ;opr = PopFromStack ( ) ;}s++ ;}}Uart_Printf("\nOut of while loop s = %s",s);while ( top != -1 )/*While stack is not empty*/{opr = PopFromStack ( ) ;*( t ) = opr ;t++ ;Uart_Printf(t);}t++ ;Uart_Printf("\nEnd of poc s=%s,t=%s",s,t);}/*link push(link stack, int value){link newnode;newnode = (link) malloc( sizeof(s_list));if(!newnode){printf("\nMemory allocation failure!");return NULL;}newnode->data = value;newnode->next = stack;stack = newnode;return stack;}link pop(link stack,int *value) {link top;if(stack != NULL){top = stack;stack = stack->next;*value = top->data;free(top);return stack;}else{*value = -1;}}*/int empty(link stack){if(stack == NULL)return 1;elsereturn 0;}int is_operator(char operator) {switch(operator){case '+':case '-':case '*':case '/':case '^':return 1;default:return 0;}}int two_result(int operator, int operand1, int operand2){switch(operator){case '+': return (operand2 + operand1);case '-': return (operand2 - operand1);case '*': return (operand2 * operand1);case '/': return (operand2 / operand1);}}void Cal(){int position = 0;int operand1 = 0;int operand2 = 0;int evaluate;Initialize ( ) ;SetExpression (input) ;Uart_Printf(s);ConvertToPostfix ( ) ;SetOutput();iposition = 0;Uart_Printf("The Output is %s",output);/*while(output[position] != '\0' && output[position] != '\n'){if(is_operator(output[position])){operand = pop(operand,&operand1);operand = pop(operand,&operand2);operand = push(operand, two_result(output[position],operand1,operand2));}elseoperand = push(operand, output[position] - 48);position ++;}operand = pop(operand, &evaluate);LCD_ChangeMode(0);ClearScreen;LCD_printf("The result is %i",evaluate);*/while(output[position] != '\0' && output[position] !='\n'){if(is_operator(output[position])){operand1 = ipop();operand2 = ipop();ipush(two_result(output[position],operand1,operand2));}else{ipush(output[position] - 48);}position ++;}evaluate = ipop();Uart_Printf("The result is %i",evaluate);if(evaluate==24){// PDC pdc;// LCD_ChangeMode(0);LCD_Cls();ClearScreen();// LCD_printf("wonderful");LCD_Refresh();SetRect(&wrect,110,60,240,130);pwonderful=CreateTextCtrl(ID_wonderText,&wrect,FONTSIZE_MIDDLE,CTRL_STYLE_ NOFRAME,NULL,NULL);SetTextCtrlText(pwonderful,wstr,TRUE);scori=scori+10;OSTimeDly(5000);}else{// PDC pdc// LCD_ChangeMode(0);LCD_Cls();ClearScreen();// LCD_printf("you are foolish!");SetRect(&wrect,130,60,240,130);pwonderful=CreateTextCtrl(ID_wonderText,&wrect,FONTSIZE_MIDDLE,CTRL_STYLE_ NOFRAME,NULL,NULL);SetTextCtrlText(pwonderful,fstr,TRUE);OSTimeDly(5000);}// Main_Task();}void ipush(int i){istack[iposition] = i;iposition ++;}int ipop(){return istack[--iposition];}/********************************c 语言随即数***********************************/static unsigned _random_number_seed[55] =/* The values here are just those that would be put in this horridarray by a call to __srand(1). DO NOT CHANGE __srand() withoutmaking a corresponding change to these initial values.*/{ 0x00000001, 0x66d78e85, 0xd5d38c09, 0x0a09d8f5, 0xbf1f87fb,0xcb8df767, 0xbdf70769, 0x503d1234, 0x7f4f84c8, 0x61de02a3,0xa7408dae, 0x7a24bde8, 0x5115a2ea, 0xbbe62e57, 0xf6d57fff,0x632a837a, 0x13861d77, 0xe19f2e7c, 0x695f5705, 0x87936b2e,0x50a19a6e, 0x728b0e94, 0xc5cc55ae, 0xb10a8ab1, 0x856f72d7,0xd0225c17, 0x51c4fda3, 0x89ed9861, 0xf1db829f, 0xbcfbc59d,0x83eec189, 0x6359b159, 0xcc505c30, 0x9cbc5ac9, 0x2fe230f9,0x39f65e42, 0x75157bd2, 0x40c158fb, 0x27eb9a3e, 0xc582a2d9,0x0569d6c2, 0xed8e30b3, 0x1083ddd2, 0x1f1da441, 0x5660e215,0x04f32fc5, 0xe18eef99, 0x4a593208, 0x5b7bed4c, 0x8102fc40,0x515341d9, 0xacff3dfa, 0x6d096cb5, 0x2bb3cc1d, 0x253d15ff};static int _random_j = 23, _random_k = 54;int rand1() //产生一个随机数//{/* See Knuth vol 2 section 3.2.2 for a discussion of this randomnumber generator.*/unsigned int temp;temp = (_random_number_seed[_random_k] += _random_number_seed[_random_j]);if (--_random_j < 0) _random_j = 54, --_random_k;else if (--_random_k < 0) _random_k = 54;return (temp & 0x7fffffff); /* result is a 31-bit value *//* It seems that it would not be possible, under ANSI rules, to *//* implement this as a 32-bit value. What a shame! */}Score(){U16 scoru[2];U16 ScoreStr[20];U16 SCStr[]={0x0053,0x0063,0x006f,0x0072,0x0065,0x0000};PDC pdc;pdc=CreateDC();// LCD_ChangeMode(DspGraMode);Int2Unicode(scori, scoru);SetRect(&SCRect,115,229,165,239);SetRect(&ScoreRect,166,229,200,239);pScore=CreateTextCtrl(ID_ScoreText,&ScoreRect,FONTSIZE_SMALL,CTRL_STYLE_N OFRAME,NULL,NULL);pSCaption=CreateTextCtrl(ID_SCaption,&SCRect,FONTSIZE_SMALL,CTRL_STYLE_N OFRAME,NULL,NULL);SetTextCtrlText(pScore,scoru,TRUE);SetTextCtrlText(pSCaption,SCStr,TRUE);DestoryDC(pdc);}/*********************************时钟显示****************************************/Times() //时钟显示更新任务{// OSTaskDel(Rtc_Disp_Task_Prio);//删除任务Rtc_Updata_Sem=OSSemCreate(1);Uart_Printf("t2");OSTaskCreate(Rtc_Disp_Task,(void *)0,(OS_STK *) &Rtc_Disp_Stack[STACKSIZE-1], Rtc_Disp_Task_Prio);Uart_Printf("t3");OSTimeDly(1000);}void Rtc_Disp_Task(void *Id) //时钟显示更新任务{POSMSG pmsg;// U16 strtime[10];INT8U err;U32 key=0;int strtimei1=20;U16 strtimei2[1];for(;;){if(Rtc_IsTimeChange(RTC_SECOND_CHANGE)){//不需要更新显示OSSemPend(Rtc_Updata_Sem, 0,&err);Int2Unicode(strtimei1, strtimei2);SetTextCtrlText(tTextCtrl,strtimei2,TRUE);strtimei1--;OSSemPost(Rtc_Updata_Sem);}if(strtimei1==0){Uart_Printf("t=%i",strtimei1);pmsg=OSCreateMessage(NULL,300, key, key);if(pmsg){Uart_Printf("pmsg");SendMessage(pmsg);}}break;// OSTimeDly(250);}}//********************************************************************//int Cal_242(){float num[4];int i;char cx[4][50];/* 得到输入,保存在浮点数组num里面*/for(i = 0; i < 4; i ++){num[i] = um[i];}/* 将num的值变成字符串的形式.为了给出最后的表达式*/for(i = 0; i < 4; i ++){sprintf(cx[i], "%d", (int)num[i]);}/* 运行函数,将得到的参数传递过去*/fun2(num, cx, 4);// TextOut(pdc,30,30,cstr[],TRUE,FONTSIZE_BIG);// LCD_printf("no answer!");return;}/* 定义函数.根据给定的内容计算24点.参数为浮点型数组(每个值),字符型数组(表达式),和整数(使用多少个数计算24点) */void fun2(float n[],char ch[][50],int m){int loop1, loop2, y, i, j;float num[4];char cc[4][50];if(m == 1){/* 如果n[0] - 24.0的绝对值小于0.0001,就认为他们相等.显示表达式的内容.退出*/if(fabs(n[0] - 24.0) < 0.0001){Uart_Printf("\nexpress:%s = 24\n",ch[0]);cc24=1;// Uart_Printf("cc24=1");return ;}}else{for(loop1 = 0; loop1 < m; loop1 ++){for(loop2 = 0; loop2 < m; loop2 ++){/* 如果loop2 = loop1,进入下轮循环(同一个数不能使用两次,因为使用n[loop]来进行运算) */if(loop2 == loop1)continue;for(y = 0; y < 4; y ++){switch(y) /* 检查y的值,和那个相符就执行case那个的子句*/{case 0: num[0] = n[loop1] + n[loop2];break;case 1: num[0] = n[loop1] - n[loop2];break;case 2: num[0] = n[loop1] * n[loop2];break;case 3: if(n[loop2] == 0) /* 除数为0,break; */break;num[0] = n[loop1] / n[loop2];break;default:break;}if(y != 3 || n[loop2] != 0) /* 除数为零的除法以外的操作,将表达式的内容存入cc[0]里面*/sprintf(cc[0],"(%s%c%s)",ch[loop1],sig[y],ch[loop2]);for(i = 0,j = 1; i < m; i ++){if(i != loop1 && i != loop2){num[j] = n[i];/* 字符串copy,将ch[i]的内容放入cc[j]里面*/strcpy(cc[j], ch[i]);j ++;}}/* 递归调用*/fun2(num, cc, m - 1);}}}}}。
算24点源代码
#include<stdio.h>#include<stdlib.h>#define Shujugeshu 10int tiny_main(int Tezhengzhi, FILE* fp_total);int heart(float fours[4], int dingwei[6], int Tezhengzhi); /*核心程序,处理一组数*/void myprint(int xuhao, int* jishu, float fours[4], int dingwei[6], FILE*fp); /*打印结果*/void AAA_maker(float fours[4], float AAA[6][6][3]); /*AAA制造者*/void BBB_maker(float AAA[6][6][3], float BBB[6][6][3][6][2], int x1, int x2); /*BBB制造者*/void CCC_maker(float BBB[6][6][3][6][2], float CCC[6][6][3][6][6], int x1, intx2, int x3, int x4, int dingwei[6], int Tezhengzhi); /*CCC制造者*/void sixs_maker(float m1, float m2, float sixs[6]); /*两个数加减乘(被乘)除(被除)六种运算出结果*/int main(){int Tezhengzhi;FILE* fp_total;if((fp_total=fopen("/Users/shengdian/Documents/C/算24/total.txt","wt"))==NULL){printf("Fail openning file!\n");return -1;}for (Tezhengzhi=-1000; Tezhengzhi<=1000; Tezhengzhi++)tiny_main(Tezhengzhi,fp_total);fclose(fp_total);return1;}int tiny_main(int Tezhengzhi, FILE* fp_total){int m1, m2, m3, m4; /*用于运算的四个数的序号*/int xuhao, i, jishu; /*每种排列的序号,,成功数目*/float QiQi[4*Shujugeshu]; /*1到Shujugeshu共十个数,每个数字出现4次*/float fours[4]; /*存储四个数的数组*/int dingwei[6]; /*定位记号,前5个为坐标,最后一个为1代表有解*/FILE *fp; /*输出文件*/char file_name[50]="/Users/shengdian/Documents/C/算24/11/";char file_name_add[20];sprintf(file_name_add, "%d.txt", Tezhengzhi);strcat(file_name, file_name_add);if((fp=fopen(file_name, "wt"))==NULL){printf("Fail openning file!\n");return -1;}for(i=1;i<=Shujugeshu;i++) /*数据初始化*/QiQi[4*i-4]=QiQi[4*i-3]=QiQi[4*i-2]=QiQi[4*i-1]=i;xuhao=1;jishu=0;for(m1=0; m1<4*Shujugeshu; m1++)for(m2=m1+1; m2<4*Shujugeshu; m2++)for(m3=m2+1; m3<4*Shujugeshu; m3++)for(m4=m3+1; m4<4*Shujugeshu; m4++) /*相当于在4*NN张牌中选择4张牌*/{fours[0]=QiQi[m1];fours[1]=QiQi[m2];fours[2]=QiQi[m3];fours[3]=QiQi[m4];heart(fours, dingwei, Tezhengzhi);myprint(xuhao, &jishu, fours, dingwei, fp);xuhao++;}xuhao--;fprintf(fp, "\n~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n");fprintf(fp,"\nTezhengzhi\t:\t%d\nTotal\t\t:\t%d\nSuccess\t\t:\t%d\nSuccessRate\t:\t%2.2f%%\n", Tezhengzhi, xuhao, jishu,100.0*(float)jishu/(float)xuhao);fclose(fp);fprintf(fp_total, "%d\t\t%d\t\t%2.2f\n", Tezhengzhi, jishu,100.0*(float)jishu/(float)xuhao);return1;}int heart(float fours[4], int dingwei[6], int Tezhengzhi) /*判断一组四个数是否有解,并求具体解*/{float AAA[6][6][3], BBB[6][6][3][6][2], CCC[6][6][3][6][6]; /*4C2=6, 3C2=3, 2C2=1*/int x1, x2, x3, x4; /*四个坐标*/dingwei[5]=-1;AAA_maker(fours, AAA); /*第一步*/for(x1=0; x1<=5; x1++)for(x2=0; x2<=5; x2++)BBB_maker(AAA, BBB, x1, x2); /*第二步*/for(x1=0; x1<=5; x1++)for(x2=0; x2<=5; x2++)for(x3=0; x3<=2; x3++)for(x4=0; x4<=5; x4++) /*第三步*/{dingwei[5]=-1;CCC_maker(BBB, CCC, x1, x2, x3, x4, dingwei, Tezhengzhi);if(dingwei[5]==1)return1; /*算出24,立即返回*/}return -1;}void AAA_maker(float fours[4], float AAA[6][6][3]) /*AAA是存储的第一步运算结果*/{int x2;float sixs[6];/*前两个数不参与运算,后两个数参与运算*/ sixs_maker(fours[0], fours[1], sixs); /*2,3,(0,1)*/for(x2=0; x2<=5; x2++){AAA[0][x2][0]=fours[2];AAA[0][x2][1]=fours[3];AAA[0][x2][2]=sixs[x2];}sixs_maker(fours[0], fours[2], sixs); /*1,3,(0,2)*/for(x2=0; x2<=5; x2++){AAA[1][x2][0]=fours[1];AAA[1][x2][1]=fours[3];AAA[1][x2][2]=sixs[x2];}sixs_maker(fours[0], fours[3], sixs); /*1,2,(0,3)*/for(x2=0; x2<=5; x2++){AAA[2][x2][0]=fours[1];AAA[2][x2][1]=fours[2];AAA[2][x2][2]=sixs[x2];}sixs_maker(fours[1], fours[2], sixs); /*0,3,(1,2)*/for(x2=0; x2<=5; x2++){AAA[3][x2][0]=fours[0];AAA[3][x2][1]=fours[3];AAA[3][x2][2]=sixs[x2];}sixs_maker(fours[1], fours[3], sixs); /*0,2,(1,3)*/for(x2=0; x2<=5; x2++){AAA[4][x2][0]=fours[0];AAA[4][x2][1]=fours[2];AAA[4][x2][2]=sixs[x2];}sixs_maker(fours[2], fours[3], sixs); /*0,1,(2,3)*/for(x2=0; x2<=5; x2++){AAA[5][x2][0]=fours[0];AAA[5][x2][1]=fours[1];AAA[5][x2][2]=sixs[x2];}}void BBB_maker(float AAA[6][6][3], float BBB[6][6][3][6][2], int x1, int x2) /*BBB存储的第二步运算结果*/{int x4;float sixs[6], threes[3];threes[0]=AAA[x1][x2][0];threes[1]=AAA[x1][x2][1];threes[2]=AAA[x1][x2][2];sixs_maker(threes[0], threes[1], sixs); /*2,(0,1)*/for(x4=0; x4<=5; x4++){BBB[x1][x2][0][x4][0]=threes[2];BBB[x1][x2][0][x4][1]=sixs[x4];}sixs_maker(threes[0], threes[2], sixs); /*1,(0,2)*/for(x4=0; x4<=5; x4++){BBB[x1][x2][1][x4][0]=threes[1];BBB[x1][x2][1][x4][1]=sixs[x4];}sixs_maker(threes[1], threes[2], sixs); /*0,(1,2)*/for(x4=0; x4<=5; x4++){BBB[x1][x2][2][x4][0]=threes[0];BBB[x1][x2][2][x4][1]=sixs[x4];}}void CCC_maker(float BBB[6][6][3][6][2], float CCC[6][6][3][6][6], int x1, int x2, int x3, int x4, int dingwei[6], int Tezhengzhi) /*CCC存储的第三步运算结果*/ {int x5;float sixs[6];sixs_maker(BBB[x1][x2][x3][x4][0], BBB[x1][x2][x3][x4][1], sixs);for(x5=0; x5<=5; x5++){CCC[x1][x2][x3][x4][x5]=sixs[x5];if(sixs[x5]<Tezhengzhi+0.0001 && sixs[x5]>Tezhengzhi-0.0001) /*运算成功*/{dingwei[0]=x1;dingwei[1]=x2;dingwei[2]=x3;dingwei[3]=x4;dingwei[4]=x5;dingwei[5]=1;return;}}}void myprint(int xuhao, int* jishu, float fours[4], int dingwei[6], FILE *fp) {char a0[3], a1[3], a2[3], a3[3];char s0[20], s1[20], s2[20], s3[20], t[20];if(dingwei[5]!=1){fprintf(fp, "%5d.\tNO\t\t%3d,%3d,%3d,%3d\n", xuhao, (int)fours[0], (int)fours[1], (int)fours[2], (int)fours[3]);return;}fprintf(fp, "%5d.\tYes\t\t%3d,%3d,%3d,%3d", xuhao, (int)fours[0],(int)fours[1], (int)fours[2], (int)fours[3]);(*jishu)++;sprintf(a0, "%d", (int)(fours[0]));sprintf(a1, "%d", (int)(fours[1]));sprintf(a2, "%d", (int)(fours[2]));sprintf(a3, "%d", (int)(fours[3]));switch (dingwei[0]){case0: {strcpy(s0, a2);strcpy(s1, a3);strcpy(s2, a0);strcpy(s3, a1);break;}case1: {strcpy(s0, a1);strcpy(s1, a3);strcpy(s2, a0);strcpy(s3, a2);break;}case2: {strcpy(s0, a1);strcpy(s1, a2);strcpy(s2, a0);strcpy(s3, a3);break;}case3: {strcpy(s0, a0);strcpy(s1, a3);strcpy(s2, a1);strcpy(s3, a2);break;}case4: {strcpy(s0, a0);strcpy(s1, a2);strcpy(s2, a1);strcpy(s3, a3);break;}case5: {strcpy(s0, a0);strcpy(s1, a1);strcpy(s2, a2);strcpy(s3, a3);break;}}switch (dingwei[1]){case0:{strcat(s2, "+");strcat(s2, s3);break;}case1:{strcat(s2, "-");strcat(s2, s3);break;}case2:{strcat(s3, "-");strcat(s3, s2);strcpy(s2, s3);break;}case3:{strcat(s2, "*");strcat(s2, s3);break;}case4:{strcat(s2, "/");strcat(s2, s3);break;}case5:{strcat(s3, "/");strcat(s3, s2);strcpy(s2, s3);break;} }strcpy(s3, "(");strcat(s3, s2);strcat(s3, ")");strcpy(s2, s3);switch (dingwei[2]){case0:{strcpy(t, s0);strcpy(s0, s1);strcpy(s1, t);strcpy(t,s0);strcpy(s0, s2);strcpy(s2, t);break;}case1:{strcpy(t, s0);strcpy(s0, s1);strcpy(s1, t);break;}case2:break;}switch (dingwei[3]){case0:{strcat(s1, "+");strcat(s1, s2);break;}case1:{strcat(s1, "-");strcat(s1, s2);break;}case2:{strcat(s2, "-");strcat(s2, s1);strcpy(s1, s2);break;}case3:{strcat(s1, "*");strcat(s1, s2);break;}case4:{strcat(s1, "/");strcat(s1, s2);break;}case5:{strcat(s2, "/");strcat(s2, s1);strcpy(s1, s2);break;} }strcpy(s3, "(");strcat(s3, s1);strcat(s3, ")");strcpy(s1, s3);switch (dingwei[4]){case0:{strcat(s0, "+");strcat(s0, s1);break;}case1:{strcat(s0, "-");strcat(s0, s1);break;}case2:{strcat(s1, "-");strcat(s1, s0);strcpy(s0, s1);break;}case3:{strcat(s0, "*");strcat(s0, s1);break;}case4:{strcat(s0, "/");strcat(s0, s1);break;}case5:{strcat(s1, "/");strcat(s1, s0);strcpy(s0, s1);break;} }。
24点游戏 C语言(穷举法)
}
if(i==5)
{
s1= f(Data[Sx3],Data[Sx4],Sign[Fh1]);
s2 = f(s1,Data[Sx2],Sign[Fh2]);
s3= f(s2,Data[Sx1],Sign[Fh3]);
{
fprintf(fp,"第一步=%lf,%lf,%c, =%lf\n",Data[Sx1],Data[Sx2],Sign[Fh1],s1);
fprintf(fp,"第二步=%lf,%lf,%c, =%lf\n",Data[Sx3],Data[Sx4],Sign[Fh2],s2);
{
s1= f(Data[Sx1],Data[Sx2],Sign[Fh1]);
s2 = f(Data[Sx3],Data[Sx4],Sign[Fh2]);
s3 = f(s1,s2,Sign[Fh3]);
if(XD(s3,24.0))
if(XD(s3,24.0))
{
fprintf(fp,"第一步=%lf,%lf,%c, =%lf\n",Data[Sx2],Data[Sx3],Sign[Fh1],s1);
fprintf(fp,"第二步=%lf,%lf,%c, =%lf\n",s1,Data[Sx1],Sign[Fh2],s2);
s2 = f(s1,Data[Sx3],Sign[Fh,Sign[Fh3]);
if(XD(s3,24.0))
{
fprintf(fp,"第一步=%lf,%lf,%c, =%lf\n",Data[Sx1],Data[Sx2],Sign[Fh1],s1);
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
out<<"("<<obj.Q[1];
print(out,obj.Sign[1]);
out<<obj.Q[2]<<"))";
out<<obj.Q[3]<<"))";
break;
}
default:out<<"方法代码参数错误!!!";
}
out<<"="<<M;
{
Q[0]=a;
Q[1]=b;
Q[2]=c;
Q[3]=d;
method=m;
Sign[0]=s1;
Sign[1]=s2;
Sign[2]=s3;
}
ostream& operator<<(ostream& out,const Four &obj)
bool judge4(double a1,int b1,double a2,int b2,double a3,int b3,double a4);/*a1@((a2@a3)@a4)*/
bool judge5(double a1,int b1,double a2,int b2,double a3,int b3,double a4);/*a1@(a2@(a3@a4))*/
class Four
{
private:
int Sign[3];/*储存运算符*/
int Q[N2];/*储存原始顺序,即未排序前的顺序,是输出函数的依据*/
int method;/*方法的代号,记下由这四个数字得到24的一种方法(有可能有多种得到24的方法,但只选最先找到的那种方法)*/
public:
Gamer(string n,int b=C1);/*设置玩家姓名,初始化分数*/
int getScore() const;
void setScore(char c);/*对玩家分数进行加减操作*/
void print() const;/*打印玩家信息*/
};
Gamer::Gamer(string n,int b)
{
name=n;
bout=b;
score=bout;/*初始分数等于盘数*/
}
int Gamer::getScore() const
{
return score;
}
#include<iostream>
#include<cmath>/*fabs()*/
#include<cstdlib>/*exit(),srand(),rand()*/
#include<vector>/*vector*/
#include<string>/*string*/
#include<ctime>/*time()*/
case 4:/*a1@((a2@a3)@a4)*/
{
out<<obj.Q[0];
print(out,obj.Sign[0]);
out<<"(("<<obj.Q[1];
{
out<<"("<<obj.Q[0];
print(out,obj.Sign[0]);
out<<obj.Q[1]<<")";
print(out,obj.Sign[1]);
void print(ostream& out,int b);//打印算符
void GameOn();
class Gamer
{
private:
int score;/*得分*/
int bout;/*盘数*/
string name;/*姓名*/
out<<"("<<obj.Q[1];
print(out,obj.Sign[1]);
out<<"("<<obj.Q[2];
print(out,obj.Sign[2]);
bool judge2(double a1,int b1,double a2,int b2,double a3,int b3,double a4);/*(a1@(a2@a3))@a4*/
bool judge3(double a1,int b1,double a2,int b2,double a3,int b3,double a4);/*(a1@a2)@(a3@a4)*/
print(out,obj.Sign[1]);
out<<obj.Q[2]<<")";
print(out,obj.Sign[2]);
out<<obj.Q[3]<<")";
using namespace std;
const double Precision=1e-10;/*比较的精度*/
const double M=24;/*凑数结果*/
const int N1=13,N2=4;/*4个从1到13的数*/
const int C1=5,C2=10,C3=15,C4=20;/*盘数*/
break;
}
case 5:/*a1@(a2@(a3@a4))*/
{
out<<obj.Q[0];
print(out,obj.Sign[0]);
print(out,obj.Sign[2]);
out<<obj.Q[3];
break;
Hale Waihona Puke } case 3:/*(a1@a2)@(a3@a4)*/
public:
Four(int a=0,int b=0,int c=0,int d=0,int m=0,int s1=0,int s2=0,int s3=0);/*构造函数,初始化成员数据*/
void reSet(int a,int b,int c,int d,int m,int s1,int s2,int s3);
Q[2]=c;
Q[3]=d;
method=m;
Sign[0]=s1;
Sign[1]=s2;
Sign[2]=s3;
}
void Four::reSet(int a,int b,int c,int d,int m,int s1,int s2,int s3)
}
}
void Gamer::print() const
{
cout<<"玩家"<<name<<"的得分情况:"<<endl;
cout<<"盘数:"<<bout<<"\t"<<"初始分:"<<bout<<"\t"<<"最后得分:"<<score<<endl;
}
return out;
}
double count(double a1,int b,double a2,bool& abnormal)/*最基本的运算单元*/
{
switch(b)
{
case 1:return a1+a2;
{
switch(obj.method)
{
case 1:/*((a1@a2)@a3)@a4*/
{
out<<"(("<<obj.Q[0];
print(out,obj.Sign[0]);
case 2:return a1-a2;
case 3:return a1*a2;
case 4:
{
friend ostream& operator<<(ostream& out,const Four &obj);/*友元函数*/
};
Four::Four(int a,int b,int c,int d,int m,int s1,int s2,int s3)
{
Q[0]=a;
Q[1]=b;
out<<obj.Q[1]<<")";
print(out,obj.Sign[1]);
out<<obj.Q[2]<<")";
print(out,obj.Sign[2]);
bool judge(double a1,int b1,double a2,int b2,double a3,int b3,double a4,int& code);/*判断是否能凑成M*/
bool judge1(double a1,int b1,double a2,int b2,double a3,int b3,double a4);/*((a1@a2)@a3)@a4*/
class Gamer;/*玩家的信息*/
class Four;/*把满足条件的四个数及其符号储存起来*/
ostream& operator<<(ostream& out,const Four &obj);/*输出Four类的对象*/