c语言编程全局变量与现金收支账的代码
时间: 2024-02-06 21:13:04 浏览: 19
好的,下面是一个简单的C语言编程示例,用于维护一个现金收支账,其中使用了全局变量:
```c
#include <stdio.h>
// 定义全局变量
double balance = 0.0;
// 存款函数
void deposit(double amount) {
balance += amount;
printf("成功存入%.2f元,当前余额为%.2f元\n", amount, balance);
}
// 取款函数
void withdraw(double amount) {
if (balance < amount) {
printf("余额不足,取款失败!\n");
} else {
balance -= amount;
printf("成功取出%.2f元,当前余额为%.2f元\n", amount, balance);
}
}
int main() {
int choice;
double amount;
while (1) {
printf("\n1. 存款\n");
printf("2. 取款\n");
printf("3. 退出\n");
printf("请输入您的选择:");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("请输入存款金额:");
scanf("%lf", &amount);
deposit(amount);
break;
case 2:
printf("请输入取款金额:");
scanf("%lf", &amount);
withdraw(amount);
break;
case 3:
printf("感谢您的使用,再见!\n");
return 0;
default:
printf("无效的选择,请重新输入!\n");
break;
}
}
return 0;
}
```
在上面的代码中,我们定义了一个全局变量 `balance`,代表当前账户余额。然后我们实现了两个函数 `deposit` 和 `withdraw`,分别用于存款和取款,并且在函数中更新了 `balance` 的值。在主函数中,我们使用一个循环来不断地接收用户输入,根据用户的选择调用相应的函数,以达到维护现金收支账的目的。