实验2
task1
#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("202490042%04d\n",number);
}
system("pause");
return 0;
}

1.生成1-100的随机数
2.设定202490042后面为4位数字
3.抽取这个专业的任意五名学生
task2
#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;
}

1.重新设定总价为0元,如果去掉,则下次输入时,总价并不是从默认值0开始计算。
2.break结束整个循环,而continue会结束单个分支,但循环后续进程会继续执行。
3.没必要。输入错误编号则会提示输入编号无效,不会执行switch分支。
task 3
#include<stdio.h>
int main(){
char light;
while(1){
scanf("%c",&light);
getchar();
switch(light){
case 'r':printf("stop\n");break;
case 'g':printf("go go go\n");break;
case 'y':printf("wait a minute\n");break;
default:printf("something must be wrong...\n");break;}
}
return 0;
}

task4
#include <stdio.h>
#include<stdlib.h>
int main(){
double cost,total,max,min;
total=0;
max=0;
min=20000;
while(1){
scanf("%lf\n",&cost);
if(cost==-1){
break;
}
total=total+cost;
if(cost>max){
max=cost;
}
if(cost<min){
min=cost;
}
}
printf("今日累计消费总额:%lf\n",total);
printf("今日最高一笔开销:%lf\n",max);
printf("今日最低一笔开销:%lf\n",min);
system("pause");
return 0;
}

task 5
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
srand(time(0));
int luckyday;
luckyday=rand()%30+1;
int guess,count;
count=0;
printf("猜猜2025年4月哪一天是你的lucky day\n");
while(count<3){
scanf("%d",&guess);
if(guess==luckyday)
{
printf("哇,猜中了:-\n");
break;
}
if(guess>luckyday)
{
printf("你猜的日期晚了,你的lucky day在前面哦\n");
count++;
}
if(guess<luckyday)
{
printf("你猜的日期早了,你的lucky day还没到呢\n");
count++;
}
}
printf("次数用完啦。偷偷告诉你,4月你的lucky day是%d号\n",luckyday);
system("pause");
return 0;
}

task 6
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,j;
scanf("%d",&n);
for (i=n;i>=1;i--)
{
for (j=0;j<n-i;j++)
{
printf("\t");
}
for (j = 0; j < 2 * i - 1; j++)
{
printf(" 0 ");
printf("\t");
}
printf("\n");
for (j=0;j<n-i;j++)
{
printf("\t");
}
for (j=0;j<2*i-1;j++)
{
printf("<H>");
printf("\t");
}
printf("\n");
for (j=0;j<n-i;j++)
{
printf("\t");
}
for (j = 0; j < 2 * i - 1; j++)
{
printf("I I");
printf("\t");
}
printf("\n");
for (j=0;j<n-i;j++)
{
printf("\t");
}
printf("\n");
}
system("pause");
return 0;
}


浙公网安备 33010602011771号