编写一个C语言程序,实现一个简单的银行账户管理系统。用户可以选择存款,取款,查询余额,退出操作。要求使用选择结构来实现操作选择,并进行合法性检查(如取款不能超过余额等)
时间: 2024-10-11 20:16:51 浏览: 34
在C语言中,编写一个简单的银行账户管理系统可以利用函数和控制结构(如`switch-case`)。下面是一个基本的示例:
```c
#include <stdio.h>
#include <stdbool.h>
typedef struct {
float balance;
} Account;
void deposit(Account *account, float amount) {
if (amount > 0) {
account->balance += amount;
printf("Deposit successful. New balance is %.2f.\n", account->balance);
} else {
printf("Invalid deposit amount. Please enter a positive value.\n");
}
}
void withdraw(Account *account, float amount) {
if (amount > 0 && amount <= account->balance) {
account->balance -= amount;
printf("Withdrawal successful. New balance is %.2f.\n", account->balance);
} else {
printf("Invalid withdrawal request. Amount exceeds balance or not a positive number.\n");
}
}
void check_balance(Account *account) {
printf("Current balance: %.2f\n", account->balance);
}
bool exit_system() {
char choice;
printf("Do you want to exit? (y/n): ");
scanf("%c", &choice);
return choice == 'y';
}
int main() {
Account account = {0};
char user_choice;
while (!exit_system()) {
printf("\nBank Account Management System:\n");
printf("1. Deposit\n");
printf("2. Withdraw\n");
printf("3. Check Balance\n");
printf("4. Exit\n");
scanf(" %d", &user_choice);
switch (user_choice) {
case 1:
float deposit_amount;
printf("Enter deposit amount: ");
scanf("%f", &deposit_amount);
deposit(&account, deposit_amount);
break;
case 2:
float withdraw_amount;
printf("Enter withdrawal amount: ");
scanf("%f", &withdraw_amount);
withdraw(&account, withdraw_amount);
break;
case 3:
check_balance(&account);
break;
case 4:
printf("Exiting the system...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
```
在这个程序中,我们首先定义了一个`Account`结构体表示银行账户,然后分别实现了存款、取款、查看余额和退出的操作。主循环通过`switch-case`结构处理用户的输入并相应地调用各个功能。
阅读全文