实验3 C语言分支语句和循环语句编程应用
实验任务1
#include <math.h> #include <stdio.h> int main() { float a, b, c, x1, x2; float delta, real, imag; printf("Enter a, b, c: "); while(scanf("%f%f%f", &a, &b, &c) != EOF) { if(a == 0) printf("not quadratic equation.\n\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\n", x1, x2); } else { real = -b/(2*a); imag = sqrt(-delta) / (2*a); printf("x1 = %.2f + %.2fi, x2 = %.2f - %.2fi\n\n", real, imag, real, imag); } } printf("Enter a, b, c: "); } return 0; }
实验结果:
实验任务2
#include <stdio.h> #include <stdlib.h> #include <time.h> #define N 5 int main() { int x, n; srand(time(0)); n = 0; do { n++; x = rand()%10; printf("%3d", x); }while(n<N); printf("\n"); return 0; }
实验结果
实验任务3
#include <stdio.h> #include <math.h> main(){ int a,b,c,r; for(a=101; a<=200; a++){ b= sqrt(a); for(c=2; c<=b; ++c){ if(a% c==0) break; if(c==b){ r++; printf("%d\t",a); if(r%5==0) printf("\n"); } } } printf("\n101~200之间共有%d个素数.",r); }
实验结果:
实验任务4
# include<stdio.h> # include<math.h> int main(){ long x,y,z; while(printf("Enter a number:"),scanf("%ld",&x)!=EOF){ long i=0,z=0; while(x>0){ y=x%10; if(y%2!=0){ z=z+y*pow(10,i); i++; } x=x/10; } printf("new number is:%ld\n",z); } return 0; }
实验结果:
结论:将长整型数的每一个数取出分别判断是否为素数,选出是素数的数按大小排序输出
实验任务5
#include<stdio.h> int main(){ int i=1; int n; float s=0,h=1; printf("Enter n(1~10):"); while(scanf("%d",&n)!=EOF){ for(;i<=n;i++){ h=h*i; if(i>=2) h=-1*h; s=s+1/h; } printf("n=%d,s=%f\n",n,s); printf("Enter n(1~10):"); } }
实验结果:
实验任务6
#include<stdio.h> #include<stdlib.h> #include<time.h> int main(){ int a,x,y=1; srand(time(0)); x=rand()%31+1; printf("猜猜2020年12月哪一天会是你的luck day\n"); printf("开始喽,你有三次机会,猜吧(1~31): "); scanf("%d",&a); while(y<3){ if(a==x){ printf("你猜的日期是正确的!\n"); break; } else if(a>x) printf("你猜的日期晚了,luck day悄悄溜到前面啦\n"); else printf("你猜的日期早了,luck day还没到呢\n"); printf("再猜(1~31): "); scanf("%d",&a); y++; } if (y>=3) printf("次数用完了,偷偷告诉你:12月,你的luck day是:%d",x); return 0; }
实验结果: