实验三_C语言函数应用编程
实验一
源代码
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<windows.h>
#define N 80
void print_text(int line,int col,char text[]);
void print_spaces(int n);
void print_blank_lines(int n);
int main()
{
int line,col,i;
char text[N]="hi,November~";
srand(time(0));
for(i=1;i<=10;i++)
{
line=rand()%25;
col=rand()%80;
print_text(line,col,text);
Sleep(1000); //暂停1000ms
}
return 0;
}
//打印n个空格
void print_spaces(int n)
{
int i;
for(i=1;i<=n;i++)
printf(" ");
}
//打印n个空白行
void print_blank_lines(int n)
{
int i;
for(i=1;i<=n;i++)
{
printf("\n");
}
}
//在第line行第col列打印一段文本
void print_text(int line,int col,char text[])
{
print_blank_lines(line-1);//打印(line-1)行空行
print_spaces(col-1);// 打印(col-1)列空格
printf("%s",text);//在第line行,col列输出text中字符串
}
运行结果

功能:一定时间间隔输出 hi,November~ , 且之间的空格和行数均随机。
实验二
源代码
#include<stdio.h>
long long fac(int n);
int main()
{
int n,i;
scanf("%d",&n);
for(i=1;i<=n;i++)
printf("%d! = %lld\n",i,fac(i));
return 0;
}
long long fac(int n)
{
static long long p=1;
p*=n;
return p;
}
运行结果

static变量特征:静态变量,使每一次进入函数定义时其中静态变量p的值延续上一次的继续运算,不会重置。
实验三
源代码
#include<stdio.h>
long long func(int n);
int main()
{
int n;
long long f;
while(scanf("%d",&n)!=EOF)
{
f=func(n);//f=2^n-1
printf("n = %d , f = %lld\n",n,f);
}
return 0;
}
long long func(int n)
{
//2^n-1=2*(2^n-1-1)+1
if(n==1)
return 1;
else
return func(n-1)*2+1;
}
运行结果

实验四
源代码
#include<stdio.h>
int func(int n,int m);
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
printf("n = %d , m = %d , ans = %d\n",n,m,func(n,m));
return 0;
}
int func(int n,int m)
{
//n!/m!(n-m)!
if(n==m||m==0)
return 1;
else
return func(n-1,m)+func(n-1,m-1);
}
运行结果

实验五
源代码
#include<stdio.h>
void move(unsigned nth,char from,char to);
void hanoi(unsigned n,char from,char temp,char to);
static int m=0;
int main()
{
int n,i;
char from='A',temp='B',to='C';
while(scanf("%d",&n)!=EOF)
{
m=0;
hanoi(n,from,temp,to);
printf("%d\n",m);
}
return 0;
}
void hanoi(unsigned n,char from,char temp,char to)
{
if(n==1)
move(n,from,to);
else
{
hanoi(n-1,from,to,temp);
move(n,from,to);
hanoi(n-1,temp,from,to);
}
}
void move(unsigned nth,char from,char to)
{
printf("%u : %c ---> %c\n",nth,from,to);
m++;
}
运行结果

实验六
源代码
#include<stdio.h>
#include<stdlib.h>
long func(long s);
int main()
{
long s,t;
printf("Enter a number: ");
while(scanf("%ld",&s)!=EOF)
{
func(s);
printf("Enter a number: ");
}
return 0;
}
long func(long s)
{
int i=1,m=1;
int x[100]={'\0'};
while(s!=0)
{
x[i]=s%10;
s/=10;
i++;
m++;
}
printf("New number is: ");
for(i=m;i>=1;i--)
{
if(x[i]%2!=0)
printf("%d",x[i]);
}
printf("\n\n");
}
运行结果

浙公网安备 33010602011771号