实验二 C语言控制语句应用编程
实验任务一
//task1.c #include<stdio.h> #include<stdlib.h> #include<time.h> #define N 5 int main() { int number; int i; srand(time(0)); for(i = 0;i < N;++i) { number = rand()%500 + 1; printf("20228329%04d\n",number); } system("pause"); return 0; }
问题一:解释line15代码的功能
答:从1-500中随机选一个数赋值给number.
问题二:这个程序的功能是什么?
答:随机生成5个形式为20228329xxxx的数(202283290001~202283290500)
实验任务二
//task2.c #include<stdio.h> #include<stdlib.h> #include<time.h> #define N 3 int main() { int i ,x,j; printf("猜猜2022年11月哪一天会是你的lucky day"); printf("开始喽,你有三次机会,猜吧(1-30):"); scanf_s("%d", &x); srand(time(0)); j = rand() % 30 + 1; printf("%d", x); for (i = 1;i < 3;i++) { if (x == j) { printf("哇,猜中了:-)");break; } else if(x<j) { printf("你猜的日期早了,你的lucky day还没到呢\n"); printf("再猜(1-30):"); scanf_s("%d", &x); continue; } else if (x > j) { printf("你猜的日期晚了,你的lucky day已经过啦\n"); printf("再猜(1-30):"); scanf_s("%d", &x); continue; } } if (i == 3) printf("次数用完啦,偷偷告诉你:11月,你的lucky day是%d号", j); system("pause"); return 0; }
实验任务三
#include<stdio.h> #include<stdlib.h> int main() { char a,i; for(i=1;i>=1;++i) { a = getchar(); getchar(); if (a == 'y')printf("wait a minute\n"); else if (a == 'g')printf("go go go\n"); else if (a == 'r')printf("stop!\n"); else printf("something must be wrong"); } system("pause"); return 0; }
实验任务四
#include<stdio.h> #include<math.h> int main() { int n, i, a, b, c; float s; while (scanf_s("%d %d", &n, &a) != EOF) { s = 0; for (i = 1; i <= n; i++) { c = a; for (b = 2; b <= i; b++) c = c + c * pow(10, j - 1); s = s + (float)i / c; } printf("n = %d,a = %d,s = %lf\n", n, a, s); } return 0; }
实验任务五
//task5.c #include<stdio.h> #include<math.h> int main() { int x, y; for (x = 1;x <= 9;x++) { for (y = 1;y <= x;y++) { printf("%dx%d=%2d ", x, y, x * y); } printf("\n"); } return 0; }
实验任务六
#include<stdio.h> #include<stdlib.h> int main() { int n,i,x,y; printf("input:"); scanf("%d", &n); for (i = 0; i < n; i++) { for (y = 0; y < i ; y++)printf(" "); for (x = 0; x < (n - i) * 2 - 1; x++)printf(" O \t"); printf("\n"); for (y = 0; y < i ; y++)printf(" "); for (x = 0; x < (n - i) * 2 - 1; x++)printf("<H>\t"); printf("\n"); for (y = 0; y < i ; y++)printf(" "); for (x = 0; x < (n - i) * 2 - 1; x++)printf("I I\t"); printf("\n"); } system("pause"); return 0; }
当输入为n时:
第i行需要打印2(n-i)个小人
第i行前面需要打印i-1个\t