1. 程式人生 > 其它 >【C語言程式設計試驗與習題指導】試驗十三 2

【C語言程式設計試驗與習題指導】試驗十三 2

自動寄存櫃

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