//task1 #include <stdio.h> #include <stdlib.h> #include <time.h> #define N 5 int main() { int grade, number; int i; srand(time(0));// 以当前系统时间作为随机种子 for (i = 0; i < N; ++i) { grade = rand() % 4 + 2018; number = rand() % 999 + 1; printf("%d8330%04d\n", grade, number); } return 0; } /*问题1:取2018到2021之间一个随机整数*/ /*问题2:取1到999之间一个随机整数*/ /*问题3:随机生成从2018年到2021年之间学生的学号*/
//task2 #include<stdio.h> #include<stdlib.h> #include<time.h> #define N 3 int main() { int i; int day, guess; srand(time(0)); day = rand() % 30 + 1; printf("猜猜2022年4月哪一天会是你的lucky day?\n"); printf("\n开始喽,你有三次机会,猜吧(1~30): "); for (i = 0; i < N; ++i) { if (i != 0) printf("\n再猜(1~30): "); scanf("%d", &guess); if (day > guess) printf("\n你猜的日期早了,你的lucky day还没到呢\n"); else if (day < guess) printf("\n你猜的日期晚了,你的lucky day已经过啦\n"); else { printf("\n哇,猜中了:-)\n"); break; } } if (day != guess) printf("\n次数用完啦,偷偷告诉你:4月,你的lucky day是%d号\n", day); return 0; }
//task3 #include<stdio.h> int main() { char a, b; while (scanf("%c%c", &a, &b) != 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...\n"); } return 0; }
//task4 #include<stdio.h> int main() { int n, a; double s, i, j; while (scanf("%d%d", &n, &a) != EOF) { getchar(); s = 0; j = 0; for (i = 1; i <= n; ++i) { j = j * 10 + a; s += i / j; } printf("n = %d, a = %d, s = %f\n\n", n, a, s); } return 0; }
//task5 #include<stdio.h> int main() { int line, column, s; for (line = 1; line <= 9; ++line) { for (column = 1; column <= line; ++column) { s = column * line; printf("%d*%d = %2d ", column, line, s); } printf("\n"); } return 0; }
//task6_1 #include<stdio.h> int main() { int n, i; printf("Input n:"); scanf("%d", &n); for (i = 1; i <= n; i++) { printf(" O \n"); printf("<H>\n"); printf("I I\n\n"); } return 0; }
//task6_2 #include<stdio.h> int main() { int n, i; printf("Input n:"); scanf_s("%d", &n); for (i = 1; i <= n; i++) { printf(" O "); } printf("\n"); for (i = 1; i <= n; i++) { printf("<H> "); } printf("\n"); for (i = 1; i <= n; i++) { printf("I I "); } return 0; }
//task6_3 #include<stdio.h> int main() { int n, m, i, j; printf("Input n:"); scanf_s("%d", &n); for (j = 1; j <= n; j++) { m = 2 * (n - j) + 1; for (i = 1; i <= j - 1; i++) { printf(" "); } for (i = 1; i <= m; i++) { printf(" O "); } printf("\n"); for (i = 1; i <= j - 1; i++) { printf(" "); } for (i = 1; i <= m; i++) { printf("<H> "); } printf("\n"); for (i = 1; i <= j - 1; i++) { printf(" "); } for (i = 1; i <= m; i++) { printf("I I "); } printf("\n"); } return 0; }
实验总结:
1.随机数的设置与使用,循环的嵌套。
2.注意回车计为一个输入项时对循环造成的影响,用getchar()可吸收。