c语言编写一个简单ATM 使用循环语句和判断语句以及分支语句进行编写
时间: 2024-11-15 13:33:55 浏览: 23
在C语言中,我们可以创建一个简单的ATM模拟程序来演示基本的交互逻辑。这个程序通常包括存款、取款和查询余额等功能。这里是一个简化的例子:
```c
#include <stdio.h>
typedef struct {
float balance;
} Account;
void deposit(Account *account, float amount) {
account->balance += amount;
printf("Deposit successful! New balance: %.2f\n", account->balance);
}
void withdraw(Account *account, float amount) {
if (amount <= account->balance) {
account->balance -= amount;
printf("Withdrawal successful! New balance: %.2f\n", account->balance);
} else {
printf("Insufficient balance.\n");
}
}
void check_balance(Account *account) {
printf("Current balance: %.2f\n", account->balance);
}
int main() {
Account my_account = {0.0}; // 初始化余额为0
int choice;
while (1) {
printf("\nATM Menu:\n1. Deposit\n2. Withdraw\n3. Check Balance\n4. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
float deposit_amount;
printf("Enter deposit amount: ");
scanf("%f", &deposit_amount);
deposit(&my_account, deposit_amount);
break;
case 2:
float withdraw_amount;
printf("Enter withdrawal amount: ");
scanf("%f", &withdraw_amount);
withdraw(&my_account, withdraw_amount);
break;
case 3:
check_balance(&my_account);
break;
case 4:
printf("Thank you for using the ATM. Goodbye!\n");
return 0; // 结束程序
default:
printf("Invalid option. Please try again.\n");
}
}
return 0;
}
```
在这个示例中,我们定义了一个`Account`结构体,并通过`deposit`, `withdraw`, 和 `check_balance` 函数实现了基本功能。用户在主循环中选择操作,然后根据输入调用相应的函数。
阅读全文