PrintN函数实现
实现一个函数PrintN,使得传入一个正整数N的参数后,能顺序打印从1到N的全部正整数。
-
途径1:通过循环实现;
-
途径2:通过递归实现。
1.循环实现
#include<stdio.h>
#include<stdlib.h>
void PrintN(int N);
int main()
{
int N;
scanf_s("%d", &N);
PrintN(N);
system("pause");
}
void PrintN(int N)
{
for (int i = 0; i <= N; i++) {
printf("%d\n", i);
}
return;
}
2.递归实现
#include<stdio.h>
#include<stdlib.h>
void PrintM(int M);
int main()
{
int M;
scanf_s("%d", &M);
PrintM(M);
system("pause");
}
void PrintM(int M)
{
if (M) {
PrintM(M - 1);
printf("%d\n", M);
}
return;
}
##编译过程中出现的问题
-
环境:Windows 10 Professional+ Visual Studio 2015
-
使用
scanf
编译失败,查阅资料后改为scanf_s
; -
递归算法约在变量为4760之后出现程序终止甚至异常中断现象。
##参考资料
https://zhidao.baidu.com/question/123882045.html (
scanf
与scanf_s
)