实验三
task-1
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<unistd.h>
#define N 80
void printText(int line,int col, char text[]);
void printSpaces(int n);
void printBlanklines(int n);
int main()
{
int line, col, i;
char text[N]= "hi,May~";
srand(time(0));
for(i=1;i<=10;++i)
{
line = rand()%25;
col = rand()%80;
printText(line,col,text);
sleep(1);
}
return 0;
}
void printSpaces(int n)
{
int i;
for(i=1;i<=n;i++)
printf(" ");
}
void printBlanklines(int n)
{
int i;
for(i=1;i<=n;i++)
printf("\n");
}
void printText(int line,int col,char text[])
{
printBlanklines(line-1);
printSpaces(col-1);
printf("%s",text);
}
每隔一秒在屏幕上打印出1个随机位置的"hi, May~",共十个
task-2.1
#include <stdio.h>
#include<stdlib.h>
long long fac(int n);
int main()
{
int i, n;
printf("Enter n: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i)
printf("%d! = %lld\n", i, fac(i));
system("pause");
return 0;
}
long long fac(int n)
{
static long long p = 1;
printf("p=%11d\n",p);
p = p * n;
return p;
}
task-2.2
#include <stdio.h>
#include<stdlib.h>
int func(int, int);
int main()
{
int k = 4, m = 1, p1, p2;
p1 = func(k, m);
p2 = func(k, m);
printf("%d,%d\n", p1, p2);
system("pause");
return 0;
}
int func(int a, int b)
{
static int m = 0, i = 2;
i += m + 1;
m = i + a + b;
return m;
}
static变量即可用作静态局部变量又可用作静态全局变量。
task-3
#include <stdio.h>
long long fun(int n);
int main()
{
int n;
long long f;
while (scanf("%d", &n) != EOF)
{
f = fun(n);
printf("n = %d, f = %lld\n", n, f);
}
return 0;
}
long long fun(int n)
{
int i;
long long a=0,p=1;
if(n==0) a=1;
else
{
for(i=1;i<=n;i++)
{
p=p*2;
}
a=p-1;
}
return a;
}
task-4
#include<stdio.h>
#include<stdlib.h>
int i;
void hanoi(unsigned n,char from,char to,char temp);
void move(unsigned n,char from,char to);
int main()
{
unsigned n;
while(scanf("%u",&n)!=EOF)
{ i=0;
hanoi(n,'A','C','B');
printf("一共移动了%d次",i);}
system("pause");
}
void hanoi(unsigned n,char from,char to,char temp)
{ if(n==1)
move(n,from,to);
else
{
hanoi(n-1,from,temp,to);
move(n,from,to);
hanoi(n-1,temp,to,from);}
}
void move (unsigned n,char from,char to)
{ i++;
printf("%u:%c-->%c\n",n,from,to);
}
task-5
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int is_prime(int n);
int main()
{
int n,p,q,flagp,flagq;
for(n=4;n<=20;n+=2)
{
p = 1;
do
{
p++;
q=n-p;
flagp=is_prime(p);
flagq=is_prime(q);
}
while(flagq*flagp == 0);
printf("%d =%d + %d\n", n, p, q);
}
return 0;
}
int is_prime(int n)
{
int k;
for(k=2;k<=sqrt(n);k++)
if(n%k==0)
{
return 0;
}
return 1;
}
task-6
#include<stdio.h>
#include<stdlib.h>
long fun(long s);
int main()
{ long s,t;
printf("Enter a number:");
while(scanf("%ld",&s) != EOF)
{ t=fun(s);
printf("new number is:%ld\n\n",t);
printf("Enter a number:");
}
system("pause");
}
long fun(long s)
{ long i,p,t=0,x=0,m;
p=s;
while(p!=0)
{
i=p%10;
if(i%2==1)
t=t*10+i;
p/=10;
}
while(t!=0)
{ m=t%10;
x=x*10+m;
t/=10;
}
return x;
}