实验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("20256343%04d\n", random_no); } cnt++; } system("pause"); return 0; }
问题1:去掉后,每次生成同样的一组数。
问题2:保证每次生成不同的随机数。
实验任务2
#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; } if(choice==1||choice==2) total_price+=3*quantity; else if(choice==3) total_price+=5*quantity; else total_price+=2*quantity; 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; }
问题1:运行时,从第二次输入开始计算出错。
问题2:结束本次循环,进入下一次循环。即允许用户再次输入。
实验任务3
#include<stdio.h> int main() { char ch; while(scanf("%c",&ch)!=EOF){ if(ch=='r') printf("stop!\n"); else if(ch=='g') printf("go go go\n"); else if(ch=='y') printf("wait a minute\n"); else printf("something must be wrong\n"); getchar(); } return 0; }

实验任务4
#include<stdio.h> int main() { printf("输入今日开销,直到输入-1为止:\n"); float x,max=0.0,min=20000.0; float s=0.0; do{ scanf("%f",&x); if(x==-1) break; s=s+x; if(max<x) max=x; if(min>x) min=x; }while(1); printf("一天消费的总金额为:%f",s); printf("一天消费的最大金额为:%f",max); printf("一天消费的最小金额为:%f",min); return 0; }

实验任务5
#include<stdio.h> int main() { int a,b,c; while (scanf("%d %d %d",&a,&b,&c)!=EOF) { if(a+b<=c||b+c<=a||a+c<=b) printf("不能构成三角形\n"); else{ if(a==b&&b==c) printf("等边三角形\n"); if(a*a+b*b==c*c||a*a+c*c==b*b||b*b+c*c==a*a) printf("直角三角形\n"); if((a==b&&b!=c)||(a==c&&c!=b)||(b==c&&b!=a)) printf("等腰三角形\n"); } } return 0; }

实验任务6
#include<stdio.h> #include<stdlib.h> #include<time.h> int main() { int n,x; srand(time(NULL)); n=rand()%30+1; for(int i=0;i<3;i++){ scanf("%d",&x); if(n>x){ printf("你猜的日期早了,你的lucky day还没到呢\n"); } else if(n<x){ printf("你猜的日期晚了,你的lucky day在前面呢\n"); } else{ printf("哇,猜中了\n"); return 0; } if(i<2) printf("再猜(1~30):"); } printf("次数用完啦,你11月份的lucky day是:%d",n); return 0; }



浙公网安备 33010602011771号