自动寄存柜
#include <stdio.h> #include <time.h> #include <stdlib.h> struct boxs{ int id; int passwd; int is_used; }; void init_boxs(struct boxs *, int); int finding_available_boxes(struct boxs *, int); int get_coin_num(void); int create_rand_passwd(void); int main(void){ struct boxs c_box; int in_passwd, in_select, index, i, is_finded,BOX_NUM, is_over=0; srand((unsigned int)time(NULL)); printf("寄存器总数:"); scanf("%d", &BOX_NUM); struct boxs s_box[BOX_NUM]; init_boxs(s_box, BOX_NUM); while (1) { if (is_over) { break; } printf("1. 投硬币 2.输密码 0.退出 请选择: "); scanf("%d", &in_select); switch (in_select) { case 1: get_coin_num(); index = finding_available_boxes(s_box, BOX_NUM); if (index != -1) { // printf("index = %d", index); c_box.passwd = create_rand_passwd(); c_box.is_used = 1; s_box[index] = c_box; printf("寄存箱编号: %d 密码:%04d\n", index+1, c_box.passwd); } else{ printf("对不起,暂无可用空箱子!"); } break; case 2: printf("请输入密码: "); scanf("%d", &in_passwd); is_finded = 0; for (i = 0; i < BOX_NUM; i++) { if (s_box[i].is_used == 1 && s_box[i].passwd == in_passwd) { printf("%d号箱已打开\n", i+1); s_box[i].is_used = 0; is_finded = 1; break; } } if (!is_finded) { printf("密码错误.\n"); } break; case 0: printf("结束\n"); is_over = 1; break; } } return 0; } /* 初始化所有的箱子数据 */ void init_boxs(struct boxs *s_box, int BOX_NUM){ int i; for (i = 0; i < BOX_NUM; i++) { (*s_box).id = i + 1; (*s_box).is_used = 0; s_box++; } } /* 查询可用的空箱子 */ int finding_available_boxes(struct boxs *s_box, int BOX_NUM){ int i, index = -1; for (i = 0; i < BOX_NUM; i++) { if ((*s_box).is_used == 0) { index = i; break; } s_box++; } return index; } /* 获取投币数 */ int get_coin_num(void){ int r_num; while (1) { printf("投币值: "); scanf("%d", &r_num); if (r_num == 1) { return r_num; }else{ continue; } } return r_num; } /* 创建随机密码 */ int create_rand_passwd(void){ int r_num = (rand()%10) * 1000 + (rand()%10) * 100 + (rand()%10) * 10 + rand()%10; // printf("%d\n", r_num); return r_num; }