实验2 C语言分支与循环基础应用编程-1
1、实验任务1
task1.c
#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; printf("20248329%04d\n", random_no); } else { random_no = rand() % N3 + 1; printf("20248395%04d\n", random_no); } cnt++; } return 0; }
问题1:line21的功能是为了生成一个N1到N2的随机数
问题2:line25的功能是为了生成一个1到N3的随机数
问题3:这个代码可以生成随机学号
2、实验任务2
task2.c
#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、实验任务3
task3.c
#include <stdio.h> #include <math.h> int main() { char x; while(scanf("%s", &x) != EOF) { if (x == 'r') printf("stop!\n"); else if (x == 'g') printf("go go go\n"); else if (x == 'y') printf("wait a munite\n"); else printf("something must be wrong...\n"); } return 0; }
4、实验任务4
task4.c
#include <stdio.h> int main() { double expense, total = 0, maxExpense = 0, minExpense = 20000; printf("输入今日开销,直到输入-1 终止:\n"); while (1) { scanf("%lf", &expense); if (expense == -1) { break; } total += expense; if (expense > maxExpense) { maxExpense = expense; } if (expense < minExpense) { minExpense = expense; } } printf("今日累计消费总额:%.1lf\n", total); printf("今日最高一笔开销:%.1lf\n", maxExpense); printf("今日最低一笔开销:%.1lf\n", minExpense); return 0; }
5、实验任务5
task5.c
#include <stdio.h> int main() { int a, b, c; while (scanf("%d %d %d", &a, &b, &c)!= EOF) { if ((a + b <= c) || (a + c <= b) || (b + c <= a)) { printf("不能构成三角形\n"); } else { if ((a == b) && (b == c)) { printf("等边三角形\n"); } else if ((a == b) || (a == c) || (b == c)) { printf("等腰三角形\n"); } else if ((a * a + b * b == c * c) || (a * a + c * c == b * b) || (b * b + c * c == a * a)) { printf("直角三角形\n"); } else { printf("普通三角形\n"); } } } return 0; }
6、实验任务6
task6.c
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int luckyDay, guess, attempts = 3; srand(time(NULL)); luckyDay = rand() % 30 + 1; printf("猜猜 2024 年 11 月哪一天会是你的 lucky day\n"); printf("开始喽,你有三次机会,猜吧(1~30):"); while (attempts > 0) { scanf("%d", &guess); if (guess == luckyDay) { printf("哇,猜中了:)\n"); break; } else if (guess < luckyDay) { printf("你猜的日期早了,你的 lucky day 还没到呢\n"); } else { printf("你猜的日期晚了,你的 lucky day 在前面哦\n"); } attempts--; printf("再猜(1~30):"); } if (attempts == 0) { printf("次数用光啦。偷偷告诉你,11 月你的 lucky day 是 %d 号\n", luckyDay); } return 0; }