发布网友 发布时间:2022-04-23 23:05
共2个回答
热心网友 时间:2023-10-13 02:04
//这是我自己写的,在VC里可以运行。
#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
static int NUMBER;
bool Game24(int const nNum, int* arr, int nLen, int nCount, char* pOperator, bool* pFlag){
if(nCount == 1){
if(*arr == nNum){
printf("((%d %c %d) %c %d) %c %d = %d\n",
arr[0],pOperator[0],arr[1],pOperator[1],arr[2],pOperator[2],arr[3],NUMBER);
if(!(*pFlag)) *pFlag = true;
}
return *pFlag;
}
for(int i = 0; i < 4; ++i){
switch(i){
case 0:
pOperator[nCount - 2] = '+';
Game24(nNum - arr[nCount - 1], arr,nLen,nCount - 1,pOperator,pFlag);
break;
case 1:
pOperator[nCount - 2] = '-';
Game24(nNum + arr[nCount - 1], arr,nLen,nCount - 1,pOperator,pFlag);
break;
case 2:
pOperator[nCount - 2] = '*';
if( arr[nCount - 1] && !(nNum % arr[nCount - 1]))
Game24(nNum / arr[nCount - 1], arr,nLen,nCount - 1,pOperator,pFlag);
break;
case 3:
pOperator[nCount - 2] = '/';
if(arr[nCount - 1])
Game24(nNum * arr[nCount - 1], arr,nLen,nCount - 1,pOperator,pFlag);
break;
}
}
return *pFlag;
}
int fOperating(char pOpe, int x1, int x2){
switch(pOpe){
case '+': return x1 + x2;
case '-': return x1 - x2;
case '*': return x1 * x2;
case '/': return x1 / x2;
}
}
bool fGame24(int const nNum, int* arr,char* pOperator, bool* pFlag){
int nLeft = 0,nRight = 0;
char pOpe[4] = {'+','-','*','/'};
for(int l = 0; l < 4; ++l){
if(l == 3 && (!arr[1] || arr[0] % arr[1])) continue;
pOperator[0] = pOpe[l];
nLeft = fOperating(pOpe[l],arr[0],arr[1]);
for(int r = 0; r < 4; ++r){
if(r == 3 && (!arr[3] || arr[2] % arr[3])) continue;
pOperator[2] = pOpe[r];
nRight = fOperating(pOpe[r],arr[2],arr[3]);
for(int m = 0; m < 4; ++m){
if(m == 3 && (!nRight || nLeft % nRight)) continue;
pOperator[1] = pOpe[m];
if(fOperating(pOpe[m],nLeft,nRight) == nNum){
printf("(%d %c %d) %c (%d %c %d) = %d\n",
arr[0],pOperator[0],arr[1],pOperator[1],arr[2],pOperator[2],arr[3],NUMBER);
if(!(*pFlag)) *pFlag = true;
}
}
}
}
return *pFlag;
}
int main(int argc, char* argv[])
{
puts("start!\nPlease input 4 numbers:");
bool* pFlag = (bool*)malloc(1);
*pFlag = false;
bool flag = 0;
int pNum[4] = {0};
int cNum[4] = {0};
int iNum[4] = {0};
char cOpe[3] = {0};
for(int i = 0; i < 4; ++i)
scanf("%d",&pNum[i]);
puts("So, what number do you want:");
scanf("%d",&NUMBER);
puts("************************************");
for(iNum[0] = 0; iNum[0] < 4; ++iNum[0]){
for(iNum[1] = 0; iNum[1] < 4; ++iNum[1]){
if(iNum[1] == iNum[0]) continue;
for(iNum[2] = 0; iNum[2] < 4; ++iNum[2]){
if(iNum[2] == iNum[0] || iNum[2] == iNum[1]) continue;
for(iNum[3] = 0; iNum[3] < 4; ++iNum[3]){
if(iNum[3] == iNum[0] || iNum[3] == iNum[1] || iNum[3] == iNum[2]) continue;
for(int i = 0; i < 4; ++i) cNum[i] = pNum[iNum[i]];
if(Game24(NUMBER,cNum,4,4,cOpe,pFlag)) flag = true;
if(fGame24(NUMBER,cNum,cOpe,pFlag)) flag = true;
}
}
}
}
free(pFlag);
if(!flag) printf("No way can be found.\n");
puts("************************************\nEnd!");
system("pause");
return 0;
}
热心网友 时间:2023-10-13 02:05
link