实验2
任务1
1 #include <stdio.h> 2 #include<stdlib.h> 3 #include<time.h> 4 5 #define N 5 6 #define N1 80 7 #define N2 35 8 int main( ){ 9 int cnt; 10 int random_major,random_no; 11 srand(time(NULL)); 12 cnt=0; 13 while(cnt<N){ 14 random_major=rand()%2; 15 if(random_major){random_no=rand()%N1+1; 16 printf("20256343%d\n",random_no); 17 18 } 19 else{random_no=rand()%N2+1; 20 printf("20256136%04d\n",random_no); 21 22 } 23 cnt++; 24 } 25 return 0; 26 27 }
回答问题1:使得生成的学号随系统时间变化
回答问题2:生成随机学号
任务2
#include <stdio.h> int main(){ int choice,quantity; float total_price=0,amount_paid,change; while(1){ printf("\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; } 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
1 #include <stdio.h> 2 int main() 3 { 4 char color; 5 while (scanf("%c", &color) != EOF) { 6 7 if (color == 'r') 8 printf("stop!\n"); 9 else if (color == 'g') 10 printf("go go go\n"); 11 else if (color == 'y') 12 printf("wait a minute\n"); 13 else printf("something must be wrong...\n"); 14 getchar(); 15 } 16 return 0; 17 }
任务4
1 #include<stdio.h> 2 int main(){ 3 printf("输入今日开销,直到输入-1终止:\n"); 4 double i; 5 double sum=0,max=0,min=10000; 6 7 while (scanf("%lf",&i)!=EOF){ 8 if (i==-1) 9 break; 10 sum+=i; 11 if(max<i) 12 max=i; 13 if(min>i) 14 min=i; 15 16 17 18 } 19 20 printf("今日累计消费%.1f\n",sum); 21 printf("今日最高消费%.1f\n",max); 22 printf("今日最低消费%.1f\n",min); 23 24 25 26 return 0; 27 }
任务5
1 #include<stdio.h> 2 int main() 3 { int a,b,c; 4 while(scanf("%d%d%d",&a,&b,&c)!=EOF){ 5 if (a+b<=c||a+c<=b||b+c<=a) 6 printf("不能构成三角形"); 7 else{ 8 if(a==b&&b==c) 9 printf("等边三角形"); 10 else if(a*a+b*b==c*c||a*a+c*c==b*b||c*c+b*b==a*a) 11 printf("直角三角形"); 12 else if((a==b&&a!=c)||(b==c&&a!=c)||(a==c&&b!=c)) 13 printf("等腰三角形"); 14 else printf("普通三角形"); 15 16 } 17 } 18 19 20 21 return 0; 22 }
任务6
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<time.h> 4 int main() 5 { 6 int luckyday,guess,count=0; 7 srand(time(NULL)); 8 luckyday=rand()%30+1; 9 printf("猜猜2025年11月哪一天是你的luckyday\n"); 10 printf("开始喽,你有三次机会。猜吧(1~30):"); 11 while(count<3){ 12 scanf("%d",&guess); 13 count++; 14 if(guess==luckyday){ 15 printf("猜中了\n"); 16 break;} 17 else if(guess>luckyday){ 18 printf("你猜的日期晚了,你的luckyday在前面哦\n"); 19 } 20 else{printf("你的日期早了,你的luckyday还没到呢\n"); 21 } 22 printf("再猜(1~30):"); 23 24 }if(count==3) 25 printf("次数用光啦。偷偷告诉你,11月你的luckyday是%d号\n",luckyday); 26 return 0; 27 }