下面是一个简单的银行转账系统的示例代码,使用C语言编写:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ACCOUNTS 100
#define MAX_NAME_LENGTH 50
#define MAX_PIN_LENGTH 5
typedef struct {
char name[MAX_NAME_LENGTH];
char pin[MAX_PIN_LENGTH];
int balance;
} Account;
Account accounts[MAX_ACCOUNTS];
int num_accounts = 0;
void add_account() {
if (num_accounts >= MAX_ACCOUNTS) {
printf("Sorry, the maximum number of accounts has been reached.\n");
return;
}
Account new_account;
printf("Enter the name: ");
scanf("%s", new_account.name);
printf("Enter the pin: ");
scanf("%s", new_account.pin);
printf("Enter the initial balance: ");
scanf("%d", &new_account.balance);
accounts[num_accounts++] = new_account;
}
void transfer(char* from_name, char* to_name, int amount) {
int from_index = -1, to_index = -1;
for (int i = 0; i < num_accounts; i++) {
if (strcmp(accounts[i].name, from_name) == 0) {
from_index = i;
} else if (strcmp(accounts[i].name, to_name) == 0) {
to_index = i;
}
}
if (from_index == -1 || to_index == -1) {
printf("Sorry, the account does not exist.\n");
return;
}
if (accounts[from_index].balance < amount) {
printf("Sorry, insufficient balance.\n");
return;
}
accounts[from_index].balance -= amount;
accounts[to_index].balance += amount;
printf("Transfer successful.\n");
}
int main() {
int choice;
while (1) {
printf("\nBank Transfer System\n");
printf("1. Add account\n");
printf("2. Transfer\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1: add_account(); break;
case 2: transfer(accounts[num_accounts - 1].name, accounts[num_accounts - 2].name, 100); break; // For example purposes only, using the last two accounts for transfer. You should prompt the user for the account details instead.
case 3: exit(0); break; // Exit the program. You should prompt the user for the exit choice instead.
default: printf("Invalid choice.\n"); break; // Invalid choice. You should handle this case appropriately.
}
}
return 0; // Should never reach here. This is just to prevent a compile error for not having a return statement at the end of main(). You should handle the program exit appropriately instead.
}