实验三
实验任务一
①
// 生成N个0~99之间的随机整数,并打印输出 #include <stdio.h> #include <stdlib.h> #include <time.h> #define N 5 int main() { int x, n; srand(time(0)); // 以当前系统时间作为随机种子 for(n=1; n<=N; n++) { x = rand() % 100; // 生成一个0~99之间的随机整数 printf("%3d", x); } printf("\n"); return 0; }

②
// 生成N个1~31之间的随机整数,并打印输出 #include <stdio.h> #include <stdlib.h> #include <time.h> #define N 5 int main() { int x, n; srand(time(0)); // 以当前系统时间作为随机种子 for(n=1; n<=N; n++) { x = 1+rand() % 31; // 生成一个0~99之间的随机整数 printf("%3d", x); } printf("\n"); return 0; }

实验任务二
①
#include<stdio.h> #include<stdlib.h> #include<time.h> int main() { int x,n,i; printf("猜猜2021年5月哪一天会是你的lucky day\n开始喽,你有三次机会,猜吧(1~31)"); srand(time(0)); x = 1+rand()%31; for(i=1;i<=3;i++) { scanf("%d",&n); if(n>x) {printf("你猜的日期晚啦,lucky day悄悄溜到前面啦\n"); printf("再猜(1~31)\n"); } if(n<x) {printf("你猜的日期早了,lucky day还没到呢\n"); printf("再猜(1~31)") ; } } printf("\n"); printf("次数用完了。偷偷告诉你,5月,你的lucky day是\n"); printf("%d",x); return 0; }

实验任务三
//实现将一个长整型数上的奇数依次取出来// #include<stdio.h> #include<stdlib.h> int main() { int m,n,t,x,y; t=0; printf("Enter a number\n"); scanf("%d",&n); for(;n!=0;n=n/10) { m=n%10; if(m==1||m==3||m==5||m==7||m==9) t=t*10+m; if(m==0||m==2||m==4||m==6||m==8) t=t ; } for(y=0;t!=0;) {x=t%10; y=y*10+x; t=t/10; } printf("new number is:\n"); printf("%d\n",y); return 0; }



实验任务四
// 一元二次方程求解(函数实现方式) // 重复执行, 直到按下Ctrl+Z结束 #include <math.h> #include <stdio.h> // 函数声明 void solve(double a, double b, double c); // 主函数 int main() { double a, b, c; printf("Enter a, b, c: "); while(scanf("%lf%lf%lf", &a, &b, &c) != EOF) { solve(a, b, c); // 函数调用 printf("Enter a, b, c: "); } return 0; } // 函数定义 // 功能:求解一元二次方程,打印输出结果 // 形式参数:a,b,c为一元二次方程系数 void solve(double a, double b, double c) { double x1, x2; double delta, real, imag; if(a == 0) printf("not quadratic equation.\n"); else { delta = b*b - 4*a*c; if(delta >= 0) { x1 = (-b + sqrt(delta)) / (2*a); x2 = (-b - sqrt(delta)) / (2*a); printf("x1 = %.2f, x2 = %.2f\n", x1, x2); } else { real = -b/(2*a); imag = sqrt(-delta) / (2*a); printf("x1 = %.2f + %.2fi, x2 = %.2f - %.2fi\n", real, imag, real, imag); } } }

思考:否,函数有两个根,无法同时返回两个值。
实验五
#include<stdio.h> #include<math.h> double fun(int n);//函数声明 int main() { int n; double s; printf("Enter n(1~10):"); while(scanf("%d",&n)!= EOF) { s=fun(n); //函数调用 printf("n=%d, s=%f\n\n",n,s); printf("Enter n(1~10):"); } return 0; } //函数定义 double fun(int n) { int p=1; double s=0; int i; for(i=1; i<=n;i++) { p=p*i; //求阶乘 s=s+pow(-1,i-1)*1/p; //求和 } return s; }

实验任务六
#include<stdio.h> #include<math.h> int isprime(int); //函数声明 int main() { int x,y,col=0,sum; for(x=101;x<200;x++) { y=isprime(x); if(y>=101) { printf("%d ",y); col++; sum++; if(col%5==0) printf("\n");} } printf("100~200之间的素数个数为:%d",sum); return 0; }


浙公网安备 33010602011771号