算24(递归) 您所在的位置:网站首页 游览西湖断桥作文怎么写 算24(递归)

算24(递归)

2023-09-22 19:04| 来源: 网络整理| 查看: 265

题目: 1.给出4个小于10个正整数,你可以使用加减乘除4种运算以及括号把这4个数连接起来得到一个表达式。 2.现在的问题是,是否存在一种方式使得得到的表达式的结果等于24。 3.这里加减乘除以及括号的运算结果和运算的优先级跟我们平常的定义一致(这里的除法定义是实数除法)。 4.比如,对于5,5,5,1,我们知道5*(5-1/5)=24,因此可以得到24。又比如,对于1,1,4,2,我们怎么都不能得到24。

解法: 1.n 个数算 24,必有两个数先算。这两个数算的结果,和剩余 n-2 个数,就构成了 n-1 个数求 24 的问题。 2.枚举先算的两个数,以及这两个数的运算方式。 3.注意: 浮点数比较是否相等,不能用 ==

#include #include using namespace std; double a[5]; #define EPS 1e-6 bool isZero(double x){ //fabs-->绝对值 return fabs(x) if(isZero( a[0]-24 )){ return true; }else{ return false; } } double b[5]; //枚举两个数的所有组合 for(int i=0; i int m=0; for(int k=0; k //把其余数放进 b 数组里 b[m++] = a[k]; } } //加法 b[m] = a[i] + a[j]; if(count24(b, m+1)){ return true; } //减法 b[m] = a[i] - a[j]; if(count24(b, m+1)){ return true; } b[m] = a[j] - a[i]; if(count24(b, m+1)){ return true; } //乘法 b[m] = a[i] * a[j]; if(count24(b, m+1)){ return true; } //除法 if( !isZero(a[j]) ){ b[m] = a[i] / a[j]; if(count24(b, m+1)){ return true; } } if( !isZero(a[i]) ){ b[m] = a[j] / a[i]; if(count24(b, m+1)){ return true; } } } } return false; } int main() { while(true){ for(int i=0; i break; } if( count24(a, 4) ){ cout


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有