例 表达式计算
代码实现
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
int factor_value();//读入一个因子,并返回其值
int term_value();//读入一项,返回其值
int expression_value();//读入表达式并返回其值
int main()
{
cout << expression_value() << endl;
return 0;
}
int expression_value()//求一个表达式的值
{
int result = term_value();//求第一项的值
bool more = true;
while (more)
{
char op = cin.peek();//看第一个字符,不取走
if (op == '+' || op == '-')
{
cin.get();//从输入中取走一个字符
int value = term_value();
if (op == '+')
result += value;
else
result -= value;
}
else more = false;
}
return result;
}
int term_value()//求一个项的值
{
int result = factor_value();//求第一个因子的值
while (true)
{
char op = cin.peek();
if (op == '*' || op == '/')
{
cin.get();
int value = factor_value();
if (op == '*')
result *= value;
else
result /= value;
}
else
break;
}
return result;
}
int factor_value()//求第一个因子的值
{
int result = 0;
char c = cin.peek();
if (c == '(')
{
cin.get();
result = expression_value();
cin.get();
}
else
{
while (isdigit(c))//检查其c是否为十进制数字字符
{
result = 10 * result + c - '0';
cin.get();
c = cin.peek();
}
}
return result;
}
例 爬楼梯
解题思路
通过边界条件来组织无穷递归的发生。因此3种边界条件均可以。
代码实现:
#include<iostream>
using namespace std;
int N;
int stairs(int n)
{
if (n ==1)
return 1;
if (n == 2)
return 2;
else
return stairs(n - 1) + stairs(n - 2);
}
int main()
{
while (cin >> N)
{
cout << stairs(N) << endl;
}
return 0;
}
例 放苹果
解题思路
边界条件:i=0时返回1;k=0时返回0;
代码实现
#include<iostream>
using namespace std;
int f(int m, int n)
{
if (n > m)
return f(m, m);
if (m == 0)
return 1;
if (n == 0)
return 0;
else
return f(m, n - 1) + f(m - n, n);
}
int main()
{
int t, m, n;
cin >> t;
while (t--)
{
cin >> m >> n;
cout << f(m, n) << endl;
}
return 0;
}
例 算24
解题思路
代码实现:
#include<iostream>
#include<cmath>
using namespace std;
double a[5];
#define EPS 1e-6
bool isZero(double x)
{
return fabs(x) <= EPS;
}
bool count24(double a[], int n)
{//用数组a里面的n个数计算24
if (n == 1)
{
if (isZero(a[0] - 24))
return true;
else
return false;
}
double b[5];
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)//枚举两个数的组合
{
int m = 0;//还剩下m个数,m=n-2
for (int k = 0; k < n; k++)
if (k != i&&k != j)
b[m++] = a[k];//把其他数放入b
b[m] = a[i] + a[j];//把两个数的运算结果放入b
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()
{
double a[4] = { 1, 1, 1, 1 };
while (1)
{
cout << "please enter four number:" << endl;
for (int i = 0; i < 4; i++)
cin >> a[i];
if (a[0] == 0 && a[1] == 0 && a[2] == 0 && a[3] == 0)
break;
else{
if (count24(a, 4))
cout << "YES" << endl;
else
cout << "NO" << endl;
}
}
return 0;
}