酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

使用c语言设计一个简单的银行账户类,包含以下基本方法: 开户:用户可以通过构造函数或特定的方法(如openaccount)来开设一个新账户,需要设置账户的初始余额(默认为0)。 存款:提供一个deposit方法,获取该账户,允许用户向账户中存入一定金额。 取款:提供一个withdraw方法,允许用户从账户中取出一定金额,但需要注意账户余额不能小于取款金额,否则应抛出余额不足异常。 查询余额:提供一个getbalance方法,用于返回当前账户的余额。

```c #include <stdio.h> #include <stdlib.h> typedef struct BankAccount { int balance; } BankAccount; BankAccount* openaccount(int initial_balance) { BankAccount* account = (BankAccount*)malloc(sizeof(BankAccount)); if (account == NULL) { printf("Error: Unable to allocate memory for the account.\n"); exit(1); } account->balance = initial_balance; return account; } void deposit(BankAccount* account, int amount) { if (amount <= 0) { printf("Error: Deposit amount must be positive.\n"); return; } account->balance += amount; } void withdraw(BankAccount* account, int amount) { if (amount <= 0) { printf("Error: Withdrawal amount must be positive.\n"); return; } if (account->balance < amount) { printf("Error: Insufficient balance.\n"); return; } account->balance -= amount; } int getbalance(BankAccount* account) { return account->balance; } int main() { BankAccount* my_account = openaccount(1000); // 开户,初始余额为1000 deposit(my_account, 500); // 存款500 printf("Current balance: %d\n", getbalance(my_account)); // 查询余额 withdraw(my_account, 200); // 取款200 printf("Current balance: %d\n", getbalance(my_account)); // 查询余额 free(my_account); // 释放内存 return 0; } ``` [2024-08-08 14:47:08 | AI写代码神器 | 436点数解答]

相关提问