递归:
- #include <iostream>
- using namespace std;
- int fun(int n)
- {
- if (n == 0)
- return 1;
- else
- return n * fun(n-1);
- }
- int main()
- {
- for (int i = 0; i < 6; i++)
- {
- cout<<fun(i)<<endl;
- }
-
- return 0;
- }
非递归:
- #include <iostream>
- using namespace std;
- int fun(int n)
- {
- int result = 1;
- for (int i = n; i > 0; i--)
- {
- result *= i;
- }
- return result;
- }
- int main()
- {
- for (int i = 0; i < 6; i++)
- {
- cout<<fun(i)<<endl;
- }
-
- return 0;
- }
2.用递归和非递归方式计算下面函数的值。
递归:
- #include <iostream>
- using namespace std;
- int fun(int m, int n)
- {
- if (m == 1)
- return n;
- if (n == 1)
- return m;
- return fun(m-1, n) + fun(m, n - 1);
- }
- int main()
- {
- for (int i = 1; i < 6; i++)
- {
- for (int j = 1; j < 6; j++)
- {
- cout<<fun(i, j)<<" ";
- }
- cout<<endl;
- }
-
- return 0;
- }
非递归:
- #include <iostream>
- using namespace std;
- int fun(int m, int n)
- {
- int result;
- int **arr;
- arr = new int *[m]; //申请的行
- for (int i = 0; i < m; i++) //申请列
- {
- arr[i] = new int [n];
- }
-
- for (i = 0; i < m; i++)
- {
- arr[i][0] = i+1;
- }
- for (i = 0; i < n; i++)
- {
- arr[0][i] = i+1;
- }
- for (i = 1; i < m; i++)
- {
- for (int j = 1; j < n; j++)
- {
- arr[i][j] = arr[i-1][j] + arr[i][j-1];
- }
- }
- result = arr[m-1][n-1];
-
- for (i = 0; i < m; i++) //释放行
- {
- delete arr[i];
- arr[i] = NULL;
- }
- delete []arr; //释放整个数组
- arr = NULL;
- return result;
- }
- int main()
- {
- for (int i = 1; i < 6; i++)
- {
- for (int j = 1; j < 6; j++)
- {
- cout<<fun(i, j)<<" ";
- }
- cout<<endl;
- }
-
- return 0;
- }
3. 有两个数组A,B,元素相同,但是顺序不同,写一段代码判断判断A中元素分别与B中那个元素匹配。
- #include <iostream>
- using namespace std;
- void match(int *a, int *b, int n)
- {
- int i = 0, j;
- while (i < n)
- {
- j = 0;
- while (j < n)
- {
- if (a[i] == b[j])
- {
- cout<<"a["<<i<<"]"<<" match "<<"b["<<j<<"]"<<endl;
- }
- j++;
- }
- i++;
- }
- }
- int main()
- {
- int a[5] = {1,2,3,4,5};
- int b[5] = {4,2,1,5,3};
- match(a, b, sizeof(a)/sizeof(a[0]));
-
- return 0;
- }
4. 判断水仙花数。水仙花数是一个三位数ABC,它满足的条件是:ABC=A^3 + B^3 + C^3。
- #include <iostream>
- using namespace std;
- void shuixianhua()
- {
- int arr[3]; //用于存储个位、十位、百位的数字
- for (int i = 100; i < 1000; i++)
- {
- int j = 0;
- int n = i;
- while (n)
- {
- arr[j++] = n % 10;
- n /= 10;
- }
-
- int sum = 0;
- for (int k = 0; k < 3; k++)
- {
- sum += arr[k] * arr[k] * arr[k];
- }
- if (sum == i)
- {
- cout<<i<<endl;
- }
- }
- }
- int main()
- {
- shuixianhua();
-
- return 0;
- }
阅读(681) | 评论(0) | 转发(0) |