实验2 C语言分支与循环基础应用编程

实验任务1

1.源代码

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 5
int main1() {
    int number;
    int i;
    srand(time(0));     // 以当前系统时间作为随机种子
    for (i = 0; i < N; ++i) {
        number = rand() % 100 + 1;
        printf("20490042%04d\n", number);
    }
    return 0;
}

2.运行结果

1

3.Q&A

Q1:这个程序的功能是什么?
A1:随机生成并打印5个带有固定前缀20490042和4位随机后缀的学号。

Q2:解释lin13代码的功能。
A2:number = rand() % 100 + 1;的功能是生成一个介于1到100之间(包含1和100)的伪随机整数,并将其赋值给变量number。

Q3:解释line14使用格式符%04d起到什么作用。
A3:使用格式符%04d的作用是指定输出的整数宽度为4位如果生成的随机数不足4位,则会在其左侧自动填充0,以确保学号格式的整齐一致。

Q4:代码srand(time(0)); 起到什么作用?
A4:使用当前系统的日历时间作为随机数发生器的种子,如果去掉,系统会使用默认的种子,导致每次运行程序时生成的随机数序列完全相同。

实验任务2

1.源代码

#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;
}

2.运行结果

2

3.Q&A

Q1:line47代码total_price = 0;如果去掉,对程序有什么影响?
A1:如果去掉total_price = 0;,程序在完成一次购买后不会将总价清零。这将导致下一次购买时,新产生的金额会累加到前一次的total_price上,造成结账金额计算错误。

Q2:while循环中,有两处使用continue语句。解释在循环中使用continue语句,语义是什么?
A2:在 while 循环中,continue 语句的语义是立刻终止当前这一轮的循环执行,跳过循环体中剩余的代码,直接回到 while 循环的开头,重新开始下一轮循环。

实验任务3

1.源代码

#include <stdio.h>
char signal;
int main() {
	while (scanf(" %c", &signal) != EOF) {
		switch (signal)
		{
		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;
}

2.运行结果

3

实验任务4

1.源代码

#include <stdio.h>
int main() {
    double expense;
    double total = 0.0;
    double max = 0.0, min = 0.0;
    int judge = 1;
    printf("输入今日开销,直到输入-1终止:\n");
    while (1) {
        scanf("%lf", &expense);

        if (expense == -1.0) {
            break;
        }
        if (expense <= 0 || expense > 20000) {
            continue;
        }

        total += expense;

        if (judge) {
            max = expense;
            min = expense;
            judge = 0;
        }
        else {
            if (expense > max) {
                max = expense;
            }
            if (expense < min) {
                min = expense;
            }
        }
    }
    if (!judge) {
        printf("\n今日累计消费总额:%.1f\n", total);
        printf("今日最高一笔开销:%.1f\n", max);
        printf("今日最低一笔开销:%.1f\n", min);
    }
    return 0;
}

2.运行结果

4

实验任务5

1.源代码

#include <stdio.h>
int a, b, c;
int main() {
	while (scanf("%d %d %d", &a, &b, &c) != EOF) {
        if (a + b > c && a + c > b && b + c > a) {
            if (a == b && b == c) {
                printf("等边三角形\n");
            }
            else if (a == b || a == c || b == 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");
            }
        }
        else {
            printf("不能构成三角形\n");
        }
	}
    return 0;
}

2.运行结果

5

实验任务6

1.源代码

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int lucky_day, i, guess;
int main() {
	srand(time(0));
	lucky_day = rand() % 30 + 1;
	printf("猜猜2026年4月哪一天是你的lucky day\n");
	printf("开始喽,你有3次机会,猜吧(1~30):");
    for (i = 0; i < 3; i++) {
        if (i > 0) {
            printf("再猜(1~30):");
        }
        scanf("%d", &guess);
        if (guess == lucky_day) {
            printf("\n哇,猜中了:)\n");
            break;
        }
        else if (guess < lucky_day) {
            printf("\n你猜的日期早了,你的lucky day还没到呢\n");
        }
        else {
            printf("\n你猜的日期晚了,你的lucky day在前面哦\n");
        }
        
    }
    if (i == 3) {
        printf("\n次数用光啦。4月你的lucky day是%d号\n", lucky_day);
    }
    return 0;
}

2.运行结果

6_1

6_1

实验总结

在任务2和任务3中,通过合理运用continue进行下一轮循环以及使用break在达成目标时循环使得程序能在交互中做出合理的返回。

在任务4中,并没有要求把一天所有的开销都存入数组,而是采用了一边读取、一边累加并实时比较更新极值的算法,对于处理这类连续的数据非常高效简洁。
不仅如此,在一开始尝试double min = 0.0时,后续不论如何赋值最小价格都不会比0小,所以引入的判断变量judge为第一轮最值赋值:

int judge = 1;
//前略
if (judge) {
    max = expense;
    min = expense;
    judge = 0;
}
else {
    if (expense > max) {
        max = expense;
    }
    if (expense < min) {
        min = expense;
}

在第一轮赋值后,judge = 1,则后续利用else后的语句进行赋值。

在任务6中,设计的算法实际上实现了一个带有反馈机制的查找过程,通过每次对输入数据给出早或晚的判定,引导下一次输入缩小范围,本质是数学中二分法的程序化语言表达。
在运行程序时每次重新猜测都要重新运行程序,并缺少对结果的统计,所以可以有以下优化:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    int lucky_day, guess, i;
    char play_again;
    int total_games = 0;         
    int win_games = 0;            
    int total_guesses_in_wins = 0; 
    srand(time(0));
    printf("猜猜2026年4月哪一天是你的lucky day.v2\n");
    do {
        lucky_day = rand() % 30 + 1;
        total_games++; 
        int current_guesses = 0; 
        int is_win = 0;          
        printf("\n--- 第 %d 局游戏开始 ---\n", total_games);
        printf("开始喽,你有3次机会,猜吧(1~30):");
        for (i = 0; i < 3; i++) {
            if (i > 0) {
                printf("再猜(1~30):");
            }
            scanf("%d", &guess);
            current_guesses++;
            if (guess == lucky_day) {
                printf("\n哇,猜中了:)\n");
                is_win = 1;    
                win_games++;     
                total_guesses_in_wins += current_guesses; 
                break;
            }
            else if (guess < lucky_day) {
                printf("\n你猜的日期早了,你的lucky day还没到呢\n");
            }
            else {
                printf("\n你猜的日期晚了,你的lucky day在前面哦\n");
            }
        }
        if (!is_win) {
            printf("\n次数用光啦。4月你的lucky day是 %d 号\n", lucky_day);
        }
        printf("\n是否再来一局?(输入 Y 继续,其他任意键退出):");
        scanf(" %c", &play_again);
    } while (play_again == 'Y' || play_again == 'y');

    printf("\n========== 游戏数据报告 ==========\n");
    printf("总对局数: %d 局\n", total_games);
    printf("获胜局数: %d 局\n", win_games);
    if (total_games > 0) {
        double win_rate = (double)win_games / total_games * 100.0;
        printf("总体胜率: %.1f%%\n", win_rate);
    }
    if (win_games > 0) {
        double avg_guesses = (double)total_guesses_in_wins / win_games;
        printf("获胜局平均猜测次数: %.1f 次\n", avg_guesses);
    }
    else {
        printf("获胜局平均猜测次数: N/A (未获胜)\n");
    }
    printf("==================================\n");
    printf("感谢游玩,期待下次再见!\n");
    return 0;
}

7
通过在原有的猜数字程序外层包裹一个do——while循环,并在程序最开头声明几个用于统计的全局性质变量以实现优化。

posted @ 2026-04-01 13:30  Anchorite404  阅读(13)  评论(0)    收藏  举报