实验2
#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() % 100 + 1;
printf("20490042%04d\n", number);
}
return 0;
}

Q1:生成一个1到100的随机整数
Q2:将生成的随机数补在此处,不足四位前面补0
Q3:随机输出四位学员编号
#include <stdio.h> int main() { int choice, quantity; float total_price = 0, amount_paid, change; while (1) { printf("\n自动饮料售卖机菜单:\n"); printf("1. 可乐 - 3 元/瓶\n"); printf("2. 雪碧 - 3 元/瓶\n"); printf("3. 橙汁 - 5 元/瓶\n"); printf("4. 矿泉水 - 2 元/瓶\n"); printf("0. 退出购买流程\n"); printf("请输入饮料编号: "); scanf("%d", &choice); if (choice == 0) break; if (choice < 1 || choice > 4) { printf("无效的饮料编号,请重新输入。\n"); continue; } printf("请输入购买的数量: "); scanf("%d", &quantity); if (quantity < 0) { printf("购买数量不能为负数,请重新输入。\n"); continue; } switch (choice) { case 1: case 2: total_price += 3 * quantity; break; case 3: total_price += 5 * quantity; break; case 4: total_price += 2 * quantity; break; } printf("请投入金额: "); scanf("%f", &amount_paid); change = amount_paid - total_price; printf("本次购买总价: %.2f 元\n", total_price); printf("找零: %.2f 元\n", change); total_price = 0; } printf("感谢您的购买,欢迎下次光临!\n"); return 0;

Q1:将总价钱重置为0,如果去掉会使下一次购买时开始的总价格不是0,使所购买物品价格与应付价格不同
Q2:break是跳出所在循坏,continue是重新进行该循环
Q3:没有必要,该switch循环的输入已经在通过上方代码进行规范,不会出现所有case以外的情况
#include<stdio.h> int main() { char a; while((a=getchar())!=EOF){ getchar(); switch(a){ case 'g':printf("go go go\n");break; case 'r':printf("stop!\n");break; case 'y':printf("wait a minute\n");break; default:printf("wrong\n");break;} } return 0; }

#include<stdio.h> int main() { printf("输入今日开销,直到输入-1终止:\n"); double x,f,min,max; while(1){ scanf("%lf",&x); if(x<0) printf("输入无效,请重新输入\n"); else{ min=x; max=x; f=x; if(x>0) break;} } while(1){ scanf("%lf",&x); if(x==-1) break; if(x<0) printf("输入无效,请重新输入\n"); else{ if(x>max) max=x; if(x<min) min=x; f+=x;} } printf("总额%.1f\n",f); printf("最小值%.1f\n",min); printf("最大值%.1f\n",max); return 0; }

#include<stdio.h> #include<stdlib.h> #include<time.h> int main() { printf("猜一猜你的四月幸运日(1--30)\n"); int n,c,v=0; srand(time(0)); n=(rand()%100*3+2)/10+1; for(int i=0;i<3;i++) {scanf("%d",&c); if(c>n)printf("猜晚了\n"); else if(c<n)printf("猜早了\n"); else {printf("猜对了\n");v=1;} } if(v==0) printf("没猜到哦,lucky day%d",n); return 0; }

#include <stdio.h> int main() { int n, i, j; printf("input n: "); scanf("%d", &n); for (i = 0; i < n; i++) { for (j = 0; j < i * 4; j++) { printf(" "); } for (j = 0; j < n*2-1 - 2*i; j++) { printf(" O "); } printf("\n"); for (j = 0; j < i * 4; j++) { printf(" "); } for (j = 0; j < n*2-1 - 2*i; j++) { printf(" <H>"); } printf("\n"); for (j = 0; j < i * 4; j++) { printf(" "); } for (j = 0; j < n*2-1 - 2*i; j++) { printf(" I I"); } printf("\n"); } return 0; }

浙公网安备 33010602011771号