银行家算法 c语言代码 自己输入 文字是中文
时间: 2024-05-10 17:18:28 浏览: 156
银行家算法的C语言代码
以下是银行家算法的 C 语言代码,可以自己输入需要的文字:
```c
#include <stdio.h>
// 定义最大进程数和资源种类数
#define MAX_PROCESS 10
#define MAX_RESOURCE 10
// 定义全局变量
int available[MAX_RESOURCE];
int max[MAX_PROCESS][MAX_RESOURCE];
int allocation[MAX_PROCESS][MAX_RESOURCE];
int need[MAX_PROCESS][MAX_RESOURCE];
int work[MAX_RESOURCE];
int finish[MAX_PROCESS];
// 获取输入的矩阵
void get_input_matrix(int matrix[][MAX_RESOURCE], int row, int col) {
for (int i = 0; i < row; i++) {
printf("请输入第 %d 个进程/资源的分配情况,用空格分隔:\n", i + 1);
for (int j = 0; j < col; j++) {
scanf("%d", &matrix[i][j]);
}
}
}
// 打印矩阵
void print_matrix(int matrix[][MAX_RESOURCE], int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
// 计算 need 矩阵
void calculate_need_matrix(int max[][MAX_RESOURCE], int allocation[][MAX_RESOURCE], int need[][MAX_RESOURCE], int process_num, int resource_num) {
for (int i = 0; i < process_num; i++) {
for (int j = 0; j < resource_num; j++) {
need[i][j] = max[i][j] - allocation[i][j];
}
}
}
// 判断是否满足需求
int check_need(int process_num, int resource_num) {
for (int i = 0; i < process_num; i++) {
if (finish[i] == 0) {
int flag = 1;
for (int j = 0; j < resource_num; j++) {
if (need[i][j] > work[j]) {
flag = 0;
break;
}
}
if (flag) {
return i;
}
}
}
return -1;
}
// 银行家算法
void banker_algorithm(int process_num, int resource_num) {
// 初始化 work 和 finish 数组
for (int i = 0; i < resource_num; i++) {
work[i] = available[i];
}
for (int i = 0; i < process_num; i++) {
finish[i] = 0;
}
// 循环执行银行家算法
int count = 0;
while (count < process_num) {
int process_index = check_need(process_num, resource_num);
if (process_index == -1) {
printf("无法分配资源!\n");
return;
} else {
for (int i = 0; i < resource_num; i++) {
work[i] += allocation[process_index][i];
}
finish[process_index] = 1;
count++;
}
}
printf("可以分配资源!\n");
}
int main() {
// 输入资源数和进程数
int process_num, resource_num;
printf("请输入资源数和进程数,用空格分隔:\n");
scanf("%d %d", &resource_num, &process_num);
// 输入 available 矩阵
printf("请输入可用资源情况,用空格分隔:\n");
for (int i = 0; i < resource_num; i++) {
scanf("%d", &available[i]);
}
// 输入 max 矩阵
printf("请依次输入每个进程的最大需要资源数,用空格分隔:\n");
get_input_matrix(max, process_num, resource_num);
// 输入 allocation 矩阵
printf("请依次输入每个进程已经分配的资源数,用空格分隔:\n");
get_input_matrix(allocation, process_num, resource_num);
// 计算 need 矩阵
calculate_need_matrix(max, allocation, need, process_num, resource_num);
// 打印矩阵
printf("available 矩阵:\n");
print_matrix(available, 1, resource_num);
printf("max 矩阵:\n");
print_matrix(max, process_num, resource_num);
printf("allocation 矩阵:\n");
print_matrix(allocation, process_num, resource_num);
printf("need 矩阵:\n");
print_matrix(need, process_num, resource_num);
// 运行银行家算法
banker_algorithm(process_num, resource_num);
return 0;
}
```
阅读全文