实验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("20256136%04d\n", random_no);
}
cnt++;
}
return 0;
}
多次重复运行发现每次产生的随机数序列都不同
问题1:strand(time(NULL));的作用是设置随机数生成的种子
问题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 ans;
ans = 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 muse be wrong\n");
}
return 0;
}
实验任务4
include <stdio.h>
int main(){
double max=0.0, min=20000.0, total=0.0;
double cost;
printf("输入开销,到-1为止\n");
while(1){
scanf("%1f", cost);
if (cost==-1)
break;
if(cost>0.0&&cost<=20000.0)
total += cost;
if (cost<min)
min=cost;
if (cost>max)
max=cost;
}
printf("最高:%.1f\n", max);
printf("最低:%.1f\n", min);
printf("总额:%.1f\n", total);
return 0;
}
实验5
include <stdio.h>
int main(){
int a,b,c;
scanf("%d %d %d\n",&a,&b,&c);
while(1){
if(a+b>c&&a+c>b&&b+c>a){
printf("能构成三角形\n");
if(ab&&bc)
printf("等边三角形\n");
else if(ab||ac||bc){
if(aa+bbcc||aa+cc==bb||cc+bbaa)
printf("等腰直角三角形\n");
else
printf("等腰三角形\n");
}
else if(aa+b*bcc||aa+cc==bb||cc+bb==a*a)
printf("直角三角形\n");
else
printf("普通三角形\n");
}
else
printf("不能构成三角形\n");
}
return 0;
}
实验6