实验2
任务1
#include <stdio.h> #include <stdlib.h> #include <time.h> #define N 5 #define N1 397 #define N2 476 #define N3 21 int main(){ int cnt; int random_major, random_no; srand(time(NULL)); cnt = 0; while(cnt < N){ random_major = rand() % 2; if(random_major){ random_no = rand() % (N2 - N1 + 1) + N1; //随机生成一个在N1与N2间的数并赋值给 random_no // printf("20248329%04d\n",random_no); } else{ random_no = rand() % N3 + 1;//随机生成一个小于N3的数并赋值// printf("20248329%04d\n",random_no); } cnt++; } return 0; } //用于随机生成学号抽签//
21 随机生成一个在N1与N2间的数并赋值给 random_no
25 随机生成一个小于N3的数并赋值
//用于随机生成学号抽签//
任务2
// 一元二次方程求解 #include <stdio.h> #include <math.h> int main() { double a, b, c; double delta, p1, p2; // 用于保存中间计算结果 while(scanf("%lf%lf%lf", &a, &b, &c) != EOF) { if(a == 0) { printf("a = 0, invalid input\n"); continue; } delta = b*b - 4*a*c; p1 = -b/2/a; p2 = sqrt(fabs(delta))/2/a; if(delta == 0) printf("x1 = x2 = %.2g\n", p1); else if(delta > 0) printf("x1 = %.2g, x2 = %.2g\n", p1+p2, p1-p2); else { printf("x1 = %.2g + %.2gi, ", p1, p2); printf("x2 = %.2g - %.2gi\n", p1, p2); } } return 0; }
任务3
#include <stdio.h> int main() { char a; printf("交通灯颜色是?:\n"); while(scanf(" %c", &a) != EOF){ if (a == 'r'){ printf("stop!\n"); } else if (a == 'g'){ printf("go,go,go\n"); } else if (a == 'y'){ printf("wait a minute\n"); } else { printf("something must be wrong..."); } } return 0; }
任务4
#include <stdio.h> #include <math.h> int main() { double a, max = 0, min = 20000, zong = 0; printf("输入开销:\n"); while(1) { scanf("%lf",&a); if (a == -1){ break; } if (a > max){ max = a; } if (a < min){ min = a; } zong += a; } printf("最高开销为%.1lf\n",max); printf("最低开销为%.1lf\n",min); printf("总开销为%.1lf\n",zong); return 0; }
任务5
#include <stdio.h> #include <math.h> int main(){ int a, b, c; while (scanf("%d %d %d", &a, &b, &c )!=EOF) { if( (a + b) <= c || (c + b) <= a || (a + c) <= b) {printf("不能构成三角形"); } else if(a == b || b == c) {printf("等边三角形"); } else if(a == b || a == c || b == c) {printf("等腰三角形"); } else if(a*a + b*b == c*c || a*a + c*c == b*b || c*c + b*b == a*a) {printf("直角三角形"); } else { printf("普通三角形");} } return 0; }
任务6
#include <stdio.h> #include <stdlib.h> #include <time.h> int main () { int luckyday, guess, attempts = 3; srand(time(NULL)); luckyday = rand() % 30 + 1; while (attempts > 0) { printf("你猜多少(1-30):"); scanf("%d",&guess); if (guess == luckyday){ printf("猜对了\n"); return 0; } else if (guess < luckyday){ printf("猜早了\n"); } else { printf("猜晚了\n"); } attempts--; } printf("失败了,猜完了,幸运日是%d.\n",luckyday); return 0; }