以下程序运行环境:VS2010
主要实现
1、 随机产生四个1-10的随机数;
2、找出这四个数排列组合方式使之等于24,并输出计算式;
#include<stdio.h>
#include <math.h>
#include<iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
double Caculate(double x, int iop, double y)
{
if(iop==1) return x+y;
if(iop==2) return fabs(x-y); //总让大减小
if(iop==3) return x*y;
if(iop==4) return y?x/y:-9999; //避免零除
else return x?y/x:-9999;
}
double OutSolution(double x, int iop, double y)
{
if(iop==1)
{
cout<<x<<"+"<<y<<"="<<x+y<<endl;
return x+y;
}
if(iop==2)
{
if(x-y > 0)
cout<<x<<"-"<<y<<"="<<x-y<<endl;
else
cout<<y<<"-"<<x<<"="<<y-x<<endl;
return fabs(x-y);
}
if(iop==3)
{
cout<<x<<"*"<<y<<"="<<x*y<<endl;
return x*y;
}
if(iop==4)
{
cout<<x<<"/"<<y<<"="<<x/y<<endl;
return x/y;
}
else return 0;
}
int main()
{
int S[]={ //24种全排列对应的下标变量
1,2,3,4,1,2,4,3,1,3,2,4,1,3,4,2,1,4,2,3,1,4,3,2,2,1,3,4,2,1,4,3,2,3,1,4,2,3,4,1,2,4,1,3,2,4,3,1,
3,1,2,4,3,1,4,2,3,2,1,4,3,2,4,1,3,4,1,2,3,4,2,1,4,1,2,3,4,1,3,2,4,2,1,3,4,2,3,1,4,3,1,2,4,3,2,1};
double *number = new double [5]();
cout<<"输出四个1-10的随机数"<<endl;
srand(time(0));
for(int i=1; i!=5; i++)
{
number[i] = rand()%10+1;
cout<<number[i]<<" ";
}
//测试某些特殊数据
//number[1]=1;
//number[2]=5;
//number[3]=1;
//number[4]=7;
//for(int i=1; i!=5; i++)
//{
// cout<<number[i]<<" ";
//}
for(int i=0; i!=4*3*2*1*4; i+=4) //4个数字的24种全排列
{
double a=number[S[i+0]];
double b=number[S[i+1]];
double c=number[S[i+2]];
double d=number[S[i+3]];
for(int op1=1; op1!=5; op1++)
for(int op2=1; op2!=5; op2++)
for(int op3=1; op3!=5; op3++)
{
if(fabs(Caculate(Caculate(Caculate(a, op1, b), op2, c), op3, d)-24)<1e-8) //一个括号的,类似于((a+b)-c)*d
{
cout<<endl<<"solution:"<<endl;
OutSolution(OutSolution(OutSolution(a, op1, b), op2, c), op3, d);
goto success;
}
if(fabs(Caculate(Caculate(a, op1, b), op3, Caculate(c, op2, d))-24)<1e-8) // 两个括号的,类似于(a+b)*(c+d)
{
cout<<endl<<"solution:"<<endl;
OutSolution(OutSolution(a, op1, b), op3, OutSolution(c, op2, d));
goto success;
}
}
}
cout<<"failed: no solutions ! "<<endl;
success: cout<<"success"<<endl;
delete [] number;
system("pause");
return 0;
}
注意:
1、不要遗漏(a+b)*(c+d)的情况;
2、这里没有考虑有多解的情况,找到正确答案就输出;