实验二
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++;
}
return 0;
}
问题1:代码srand(time(NULL))起到了生成随机数的作用
问题2:这个程序能利用生成的随机数和固定数字组合从而达到生成随机学号的目的
task.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:total_price = 0去掉后会把上次上一次的购买总价和这次实际的总价相加生成最后的“本次购买总价”
2:continue的做用:使得continue这一行以下的所有代码跳过不运行,并重新从上一个条件语言结束位置运行
task.3
点击查看代码
#include <stdio.h>
int main(){
char ans;
while(ans!=EOF){
ans=getchar();
getchar();
if(ans=='y'){
printf("wait a minute\n");
}
else if(ans=='g'){
printf("go go go\n");
}
else if(ans=='r'){
printf("stop!\n");
}
else
printf("something must be wrong\n");
}
return 0;
}
task.4
点击查看代码
#include <stdio.h>
int main(){
double x=0,y,max,min;
printf("输入今日的开销,直到输入-1结束:\n");
scanf("%lf",&y);
max=y;
min=y;
while(y>0&&y<20000){
x=x+y;
if(y>max)max=y;
if(y<min)min=y;
scanf("%lf",&y);
}
printf("今日累计消费总额:%.1lf\n",x);
printf("今日最高一笔开销:%.1lf\n",max);
printf("今日最低一笔开销:%.1lf\n",min);
return 0;
}
task.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){
if(a*a==b*b+c*c||b*b==a*a+c*c||c*c==a*a+b*b){
printf("直角三角形");
}
else if(a==b||a==c||b==c){
printf("等腰三角形");
}
else if(a==b==c){
printf("等边三角形");
}
else{
printf("普通三角形");
}
}
else{
printf("不能构成三角形");
}
}
return 0;
}
task.6
点击查看代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 29
int main(){
int day,cnt=0;
int inportant;
srand(time(NULL));
inportant = rand() %N + 1;
printf("猜猜2025年十一月那一天是你的lucky day\n");
printf("开始喽,你有三次机会,猜吧(1~30):");
while(cnt<3){
scanf("%d",&day);
if(day<inportant){
printf("你猜的日期早了,你的lucky day还没到呢\n");
printf("再猜(1~30):");
}
else if(day>inportant){
printf("你猜的日期晚了,你的lucky day在前面呢\n");
printf("再猜(1~30):");
}
else if(day=inportant){
printf("哇,猜中了\n");
break;
}
cnt++;
}
if(cnt==3)
printf("次数用完啦,偷偷告诉你,11月你的lucky day是%d号",inportant);
return 0;
}