实验2
实验任务1
源代码

#include<stdio.h> #include<stdlib.h> #include<time.h> #define N 5 #define N1 80 #define N2 35 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()%N1+1; printf("20256343%04d\n",random_no);} else{ random_no=rand()%N2+1; printf("20256136%04d\n",random_no); } cnt++; } system("pause"); return 0;}
运行截图
问题1生成随机数
问题2先生成数并做标记,根据标记来选择输出格式,并最后两个数字随机数
实验任务2
源代码

#include<stdio.h> #include<stdlib.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_s("%d",&choice); if(choice==0) break; if(choice<1||choice>4){ printf("无效的饮料编号,请重新输入。\n"); continue;} printf("请输入购买的数量:"); scanf_s("%d",&quantity); if(quantity<0){ printf("购买的数量不能为负数,请重新输入。\n"); continue; } if( choice==1||choice==2) total_price +=3*quantity; else if(choice==3) total_price +=5*quantity; else total_price +=2*quantity; printf("请投入金额:"); scanf_s("%f",&amount_paid); change=amount_paid-total_price; printf("本次购买总价;%.2f元\n",total_price); printf("找零:%.2f元\n",change); total_price=0;} printf("感谢您的购买,欢迎下次光临!\n"); system("pause"); return 0;}
运行截图
问题1会出现累计计价的错误,上一次的总价算在下一次里
问题2跳过当前循环中continue之后的代码直接开始下一次循环
实验3
源代码

#include<stdio.h> #include<stdlib.h> int main(){ char ans; while (1){scanf_s("%c",&ans); if(ans=='r') {printf("stop!\n");} else if(ans=='y'){ printf("wait a minute\n");} else if(ans=='g'){printf("go go go\n");} else{printf("something must be wrong...\n");} getchar(); system("pause");} return 0;}
运行截图
实验任务4
源代码

1 #include<stdio.h> 2 #include<stdlib.h> 3 int main(){float x,y=0,z=0,ans=20000; 4 printf("输入今日开销,直到输入-1终止:\n"); 5 while(1){scanf_s("%f",&x); 6 if(x==-1) 7 {break;} 8 y+=x; 9 if(z<x){z=x;} 10 if(ans>x){ans=x;} 11 } 12 printf("今日累计消费总额:%.1f\n",y); 13 printf("今日最高一笔开销:%.1f\n",z); 14 printf("今日最低一笔开销:%.1f\n",ans); 15 system("pause"); 16 return 0;}
运行截图
实验任务5

1 #include<stdio.h> 2 #include<stdlib.h> 3 int main(){int a,b,c; 4 while(1){scanf_s("%d%d%d",&a,&b,&c); 5 if(a+b<=c||a+c<=b||b+c<=a) 6 {printf("不能构成三角形\n");} 7 else if(a*a==b*b+c*c||b*b==c*c+a*a||c*c==a*a+b*b) 8 {printf("直角三角形\n");} 9 else if(a==b==c) 10 {printf("等边三角形\n");} 11 else if(a==b!=c||a==c!=b||b==c!=a) 12 {printf("等腰三角形\n");} 13 getchar();} 14 system("pause"); 15 return 0;}
运行截图
实验任务6
源代码

#include<stdio.h> #include<stdlib.h> #include<time.h> int main(){ int x,y,z=0; srand(time(NULL)); x=rand()%30+1; printf("猜猜2025年11月哪一天是你的lucky day\n"); printf("开始喽,你有三次机会,请猜(1-30):"); while(z<3){scanf_s("%d",&y); z++; if(y<x) {printf("你猜的日期早了,你的lucky day还没到呢\n");} else if(y>x) {printf("你猜的日期晚了,你的lucky day在前面哦\n");} else{printf("哇,猜中了:)\n"); return 0;} if(z<30){printf("再猜(1-30):");} } printf("次数用光啦。偷偷告诉你,11月份你的lucky day是%d号\n",x); system("pause"); return 0;}
运行截图