使用while循环在C中使用递归的阶乘程序。大家好,谢谢你的宝贵回复。在while循环中使用递归函数的阶乘程序
你们都说过使用(如果条件而不是while)。其正确的我接受你的建议。那么为什么我不使用递归函数来寻找阶乘。
有人说
while(n>1)
是一个无限循环。但是在这个程序中n
的值在fact(n-1)
函数本身中递减。现在在这个程序中,我在while循环之后输入printf()
和getch()
以知道n
的值。仅当while条件变为false时,printf()
和getch()
函数才会执行。
当我运行此程序的printf()
功能和getch()
功能重复执行和printf()
函数的返回值n
= 1。所以我确定的n
值递减。那么为什么这个程序一次又一次地执行while循环呢?
- 在所有函数中,return语句是最后一个函数的终止语句。当执行到达返回语句时,执行从函数中终止并返回到被调用函数的下一行。但是在这个程序中,在执行到达返回语句之后,它将重复执行相同的函数。这是为什么?
注:我使用的Turbo C 3.0运行此程序,
#include<stdio.h>
int fact(int n)
{
int x=1;
while(n>1)
{
x=n*fact(n-1);
}
printf("N value after the while loop:%d",n);
getch();
return(x);
}
void main()
{
int n,fact1;
scanf("%d",&n);
fact1=fact(n);
printf("%d",fact1);
}