实验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("20256316%04d\n",random_no);
}
cnt++;
}
return 0;
}
运行结果
问题1:代码srand(time(NULL));用来生成随机数
问题2:这个程序的功能是在两个班中随机抽取5个学生的学号
实验任务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("请输入饮料编号:");
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:line47代码total_price = 0;如果去掉,在多次运行时会将之前的总价也算上
问题2:在循环中使用continue语句,语义是在该循环中运行完一段代码后,继续运行下一段代码
实验任务3
源代码
#include<stdio.h>
int main(){
char ans;
while((ans=getchar())!=EOF){
getchar();
if(ans=='r')
printf("stop!\n");
else if(ans=='g')
printf("go go go\n");
else if(ans=='y')
printf("wait a minute\n");
else
printf("something must be wrong...\n");
}
return 0;
}
运行结果
实验任务4
#include<stdio.h>
int main(){
double expense,total;
double max,min;
int count=0;
printf("输入今日开销,直到输入-1终止:\n");
while(1){
scanf("%lf",&expense);
if(expense==-1){
break;
}
if(expense<=0||expense>20000){
printf("输入无效,请重新输入(0<消费<=20000)\n");
continue;
}
if(count==0){
max=expense;
min=expense;
}
else{
if(expense>max){
max=expense;
}
if(expense<min){
min=expense;
}
}
total+=expense;
count++;
}
printf("今日累计消费总额:%.lf\n",total);
printf("今日最高一笔开销:%.lf\n",max);
printf("今日最低一笔开销:%.lf\n",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||a+c<=b||b+c<=a){
printf("不能构成三角形\n");
continue;
}
else{
if(a==b&&a==c)
printf("等边三角形\n");
else if(a==b&&a!=c||a==c&&a!=b||b==c&&a!=c)
printf("等腰三角形\n");
else if(a*a+b*b==c*c||a*a+c*c==b*b||b*b+c*c==a*a)
printf("直角三角形\n");
else
printf("普通三角形\n") ;
}
}
return 0;
}
运行结果
实验任务6
源代码
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
int i=0;
int day,ans;
srand((unsigned int)time(NULL));
day=rand()%30+1;
printf("猜猜2025年11月哪一天是你的lucky day\n");
printf("开始喽,你有三次机会,猜吧(1~30):");
for(i=0;i<=2;i++){
scanf("%d",&ans);
if(ans==day){
printf("哇,猜中了:)");
break;}
else if(ans<day){
printf("你猜的日期早了,你的lucky day在后面哦\n");
}
else{
printf("你猜的日期晚了,你的lucky day在前面哦\n");
}
if(i<2)
printf("再猜(1~30):");
}
if(i==3){
printf("次数用光啦。偷偷告诉你,11月你的lucky day是%d号\n",day);
}
return 0;
}