实验3
//实验任务1// #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; printf("%3d",x); } printf("\n"); return 0; }
//实验任务2// #include <stdio.h> #include <stdlib.h> #include <time.h> int main(){ int x,y; int n=1; srand(time(0)); x=rand()%32; printf("开始喽,你有三次机会,猜吧(1~31):"); for(;n<=3;n++){ scanf("%d",&y); if(y>x){ printf("你猜的日期晚了,luck day悄悄溜到前面啦"); if(n!=3){ printf("\n再猜(1~31)"); } else{ printf("\n"); } } else if(y<x){ printf("luck day还没到呢"); if(n!=3){ printf("\n再猜(1~31)"); } else{ printf("\n"); } } else if(y=x){ printf("恭喜你,猜对了!"); return 0; } } printf("\n次数用完啦。偷偷告诉你:5月,你的luck day是%d",x); return 0; }
//实验任务3// #include <stdio.h> int main(){ long long s; int t=0; int n=1; int x=1; printf("Enter a number:"); while(scanf("%lld",&s) != EOF){ int y=0; while(s!=0){ n=s%10; s=(s-n)/10; if(n%2!=0) t=t*10+n; } while(t!=0){ x=t%10; t=(t-x)/10; y=y*10+x; } printf("new number is:%d\nEnter a number:",y); } return 0; }
//实验任务4// #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; } 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); } } } //能,将33行和38行替换成返回对应的返回值,在主函数中第12行替换为printf函数solve的返回值添加合适的文本,还要把void改为float//
//实验任务5//
#include <stdio.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) { double x; int i=1,y=1; double t=0; for(i=1;i<=n;i++){ y=i*y; if(i%2==0) x=(-1/(double)y); else x=(1/(double)y); t=t+x; } return t; }
//实验任务6// #include <stdio.h> #include <math.h> int isPrime(int n); int main(){ int n,i,m,a,t=0; printf("获得两数之间的素数\n请输入两数:\n"); scanf("%d%d",&i,&n); a=i; for(;i<=n;i++){ m=isPrime(i); if(m!=0&&m!=1){ printf("%d ",m); t=t+1; if(t%5==0) printf("\n");}} printf("\n\n%d^%d之间素数个数为:%d",a,n,t); return 0; } int isPrime(int n){ int x,result; int y=2; x=sqrt(n); while(y<=x&&n%y!=0){ y=y+1; } if(y>x) return n; else return 0; }