来自网络,联系侵删
132 字
1 分钟
【课堂代码】函数2
1. 递归求阶乘 n!
题目: 编写递归函数 fun(n),求 n 的阶乘。输入一个整数 n,输出 n! 的值。若 n < 0 则输出 “input error”。
#include <iostream>
using namespace std;
long long fun(long long n); //函数的声明
int main(){ long long num ;
cin>>num; if(num<0) cout<<"input error"<<endl; else cout<<fun(num)<<endl; //函数的调用
}
long long fun(long long n) //阶乘计算{ if(n<0) //非法输入 return -1; else if(n==0||n==1) //边界 return 1; else return n*fun(n-1); //算阶乘}2. 数字反转
#include<iostream>using namespace std;void reverse(int num){ if(num<0) { cout<<'-'; reverse(-num); } else if(num==0) { return; } else { cout<<num%10; reverse(num/10); }
return;}
int main(){ int n;
cin>>n; if(n==0) cout<<0; else reverse(n); return 0;}3. 求 x 的 n 次幂(迭代法 + 递归法)
#include<iostream>
using namespace std;
float fun(float x, int n) //迭代法{ float result=1.0;
while(n--) result*=x;
return result;}
float fun_2(float x, int n) //递归法{ float result=1.0;
if(n==0) result=1.0; else result=x*fun_2(x,n-1); return result;}
int main(){ //验证三天打鱼两天晒网 小于1.01 if(fun_2(1.01, 3)*fun_2(0.99, 2)<1.01) cout<<"True"<<endl; else cout<<"False"<<endl;
int n; float x;
cin>>x>>n; cout<<fun_2(x,n)<<endl;
return 0;}4. 汉诺塔
题目: 编写递归函数 hanoi(n, a, b, c),求解汉诺塔问题。输入盘子数量 n,输出将 n 个盘子从 A 柱借助 C 柱移动到 B 柱的所有步骤,并输出总移动次数。
#include <iostream>#include <string>#include <cmath>
using namespace std;
// 前向声明函数void hanoi(int n, char a, char b, char c);void move(int n, char sourcePeg, char destinationPeg);
void hanoi(int n, char a, char b, char c) { // 基本情况:如果只有一个盘子 (n=1),直接从 A 移动到 B if (n == 1) { move(1, a, b); return; // 递归结束,返回上一层调用 }
// 递归步骤 1: 将 n-1 个盘子从源柱 (a) 移动到辅助柱 (c),目标是 c hanoi(n - 1, a, c, b);
// 递归步骤 2: 将最大的第 n 个盘子从源柱 (a) 直接移动到目标柱 (b) move(n, a, b);
// 递归步骤 3: 将 n-1 个盘子从辅助柱 (c) 移动到目标柱 (b),目标是 b hanoi(n - 1, c, b, a);}
void move(int n, char sourcePeg, char destinationPeg) { cout << "Move disk " << n << " from " << sourcePeg << " to " << destinationPeg << endl;}
int main() { int n; cout << "=========================================" << endl; cout << " Tower of Hanoi Solver (Recursive) " << endl; cout << "=========================================" << endl;
cout << "Input the Number of Disks (N): "; cin >> n;
if (n <= 0) { cout << "Invalid input. Please enter a positive integer." << endl; return 1; }
cout << "\n--- Solution Steps ---" << endl; cout << "Steps of moving " << n << " disks from A to B by means of C:" << endl;
hanoi(n, 'A', 'B', 'C');
cout << "\n=========================================" << endl; cout << "Total moves required: " << (long long)pow(2, n) - 1 << endl; cout << "=========================================" << endl;
return 0;} 分享
如果这篇文章对你有帮助,欢迎分享给更多人!
部分信息可能已经过时
相关文章 智能推荐



























