## 实验三

task1.1 源代码

#include<stdio.h>
long long fac(int n);
int main()
{
int i, n;
printf("Enter n: ");
scanf_s("%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 = p * n;
return p;
}

#include<stdio.h>
long long fac(int n);
int main()
{
int i, n;
printf("Enter n: ");
scanf_s("%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;
printf("p = %lld\n", p);
p = p * n;
return p;
}

task 1.2

#include<stdio.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);
return 0;
}
int func(int a, int b)
{
static int m = 0, i = 2;
i += m + 1;
m = i + a + b;
return (m);
}

static变量不会随着函数的结束而被释放

static变量不会被再次赋初值

#include<stdio.h>
void printSymbol(int n, char symbol)
{
for(int i=0;i<n;i++)
{
printf("%c", symbol);
}
}
int main()
{
int n;
char symbol;
while (scanf_s("%d %c", &n, &symbol) != EOF)
{
printSymbol(n, symbol); // 函数调用
printf("\n");
}
return 0;
}

#include<stdio.h>
void printSymbol(int n, char symbol)
{
if (n == 0)return;
printSymbol(n - 1, symbol);
printf("%c", symbol);
}
int main()
{
int n;
char symbol;
while (scanf_s("%d %c", &n, &symbol) != EOF)
{
printSymbol(n, symbol); // 函数调用
printf("\n");
}
return 0;
}

我认为此题迭代更好

#include<stdio.h>
long long fun(int n)
{
if (n == 0)return 0;
else
{
return 2 * fun(n - 1)+1;
}
}
int main()
{
int n;
long long f;
while (scanf_s("%d", &n) != EOF)
{
f = fun(n); // 函数调用
printf("n = %d, f = %lld\n", n, f);
}
return 0;
}

#include<stdio.h>
#include<math.h>
int isPrime(int n)
{
for(int i=2;i<=sqrt(n);i++)
{
if (n % i == 0)return 0;
}
return 1;
}
int main()
{
int sum = 0;
for(int i=101;i<=200;i++)
{
if(!isPrime(i))
{
printf("%6d", i);
sum++;
if (sum % 10 == 0)printf("\n");
}
}
printf("\n一共有%d个非素数", sum);
return 0;
}

任务5

#include<stdio.h>
#include<math.h>
long fun(long s)
{
long a=0, b=1,num=0;//a用来存放每位的数，b用来记位数
while(s>0)
{
a = s % 10;
if(a%2!=0)
{
num += a * b;
b *= 10;
}
s /= 10;
}
return num;
}
int main()
{
long s, t;
printf("Enter a number: ");
while (scanf_s("%ld", &s) != EOF)
{
t = fun(s); // 函数调用
printf("new number is: %ld\n\n", t);
printf("Enter a number: ");
}
return 0;
}

#include<stdio.h>
#include<math.h>
double jie_cheng(int x)
{
if (x == 1)return 1;
else
{
return x * jie_cheng(x - 1);
}
}
double fun(int n)
{
double sum=0;
for(int i=1;i<=n;i++)
{
if (i % 2 == 0)sum -= (1 / jie_cheng(i));
else sum += (1 / jie_cheng(i));
}
return sum;
}
int main()
{
int n;
double s;
printf("Enter n(1~10): ");
while (scanf_s("%d", &n) != EOF)
{
s = fun(n); // 函数调用
printf("n = %d, s= %f\n\n", n, s);
printf("Enter n(1~10): ");
}
return 0;
}

posted on 2021-11-24 11:09  彭涌涛  阅读(26)  评论(1编辑  收藏  举报