用C++编写

来源:百度知道 编辑:UC知道 时间:2024/05/28 06:32:50
把以下程序中的print()函数改写成等价的递归函数。
#include<iostream.h>
void print(int w)
{for(int i=1;i<=w;i++)
{for(int j=1;j<=i;j++)
cout<<i<<"";
cout<<endl;
}
}
void main()
{print(5);}

运行显示:
1
22
333
4444
55555

#include<iostream>
using namespace std;
int w;
void print(int i){
if (i>w) return;
for(int j=1;j<=i;j++)
cout<<i<<" ";
cout<<endl;
print(i+1);
}
int main(){
w=5;
print(1);
while (1);//查看结果用
return 0;
}

void print(int i,int w)
{
if(i==w)
return ;
for(int j=1;j<=i;j++)
cout<<i<<"";
cout<<endl;
print(i+1,w);
}
这算是一个强掰的递归 这个函数 确实 没有递归的必要
递归是 为了让程序 变得容易理解 更容易编写 而发明的
但在这里丝毫体现不出 递归的 优点

永远没有,递归函数会增加堆栈负担。

void print(int n)
{
int i;
if (n>1) print(n-1);
for (i = 0; i<n; i++) printf("%d",n);
putchar('\n');
}