一.函数题
6-1 计算A[n]=1/(1 + A[n-1])
float fun(int n)
{
if (n == 1)
return 1;
return 1 / (1 + fun(n - 1));
}
6-2 递归实现顺序输出整数
void printdigits(int n)
{
int count = 0;
int num1 = 0;
num1 = n;
if (n == 0)
{
printf("0");
return 0;
}
while (n)
{
n /= 10;
count++;
}
int num[100] = { 0 };
n = num1;
int count1 = 0;
while (n)
{
num[count1++] = n % 10;
n /= 10;
}
for (int i = count1 - 1; i >= 0; i--)
{
printf("%d\n", num[i]);
}
}
6-3 自然数的位数(递归版)
int NumDigit(int number)
{
if (number == 0)
return 0;
else if (number / 10 == 0)
return 1;
else
return NumDigit(number / 10) + 1;
}
6-4 分治法求解金块问题
int max(int a[], int m, int n) {
int i;
int max = a[0];
for (i = m; i < n + 1; i++) {
if (a[i] > max) {
max = a[i];
}
}
return max;
}
int min(int a[], int m, int n) {
int i;
int min = a[0];
for (i = m; i < n + 1; i++) {
if (a[i] < min) {
min = a[i];
}
}
return min;
}
6-5 汉诺塔
void hanoi(int n, char from, char to, char by)
{
void move(char x, char y);
if (n == 1)
move(from, to);
else
{
hanoi(n - 1, from, by, to);
move(from, to);
hanoi(n - 1, by, to, from);
}
}
void move(char x, char y)
{
printf("%c->%c\n",x,y);
}
6-6 重复显示字符(递归版)
void Show(int number, char symbol)
{
void Print(char ch);
if (number <= 0)
return;
if (number == 1)
Print(symbol);
else
{
Show(number - 1, symbol);
Print(symbol);
}
}
void Print(char ch)
{
printf("%c", ch);
}
6-7 显示平行四边形(右)(递归版)
文章来源:https://www.toymoban.com/news/detail-756665.html
void RtPara(int width, int height, char symbol)
{
void PrintSpace(int number);
if (width <= 0 || height <= 0)
return;
else
{
PrintSpace(height - 1);
Show(width, symbol);
putchar('\n');
RtPara(width, height - 1, symbol);
}
}
void PrintSpace(int number)
{
if (number <= 0)
return;
else
{
printf(" ");
PrintSpace(number - 1);
}
}
二.编程题
7-2 N阶楼梯上楼问题
文章来源地址https://www.toymoban.com/news/detail-756665.html
int ClimbStairs(int number)
{
if (number == 1)
return 1;
else if (number == 2)
return 2;
else
{
int dp[number+1];
dp[1] = 1;
dp[2] = 2;
int i = 0;
for (i = 3; i <= number; i++)
{
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[number];
}
}
int main()
{
int n = 0;
int ways = 0;
scanf("%d", &n);
ways = ClimbStairs(n);
printf("%d\n", ways);
}
到了这里,关于【C/PTA —— 11.函数2(课外实践)】的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!