c - 问题强制从 C 中的函数返回 -1
问题描述
在初学者的 C 类中创建银行家程序。我的所有代码都成功运行(在测试了所有案例之后),除了在循环的一部分中强制返回负数。当值通过复制返回到主程序时,它会改变余额。
函数返回
else { //If the amount to be withdrawn from the account is greater than the existing amount
printf("Error. Withdrawal must be less than account balance.\n"); //Output error message
return -1; //Return a negative one to the main program
}
在 main 中通过副本返回
case 3: //提现
printf("You are about to withdraw cash from an account.\n \n");
withdrawnAmount = withdrawal(balance); //Calling function to withdraw money from existing account
balance -= withdrawnAmount;
printf("Your new account balance is $%d\n\n", balance);
break;
解决方案
我认为在这种情况下,您应该要么return 0;
这样就不会扣除金额,如下所示:
else { //If the amount to be withdrawn from the account is greater than the existing amount
printf("Error. Withdrawal must be less than account balance.\n"); //Output error message
return 0; //Return zero to the main program
}
或者,如果您想继续使用负数,则需要在从帐户余额中扣除之前检查返回的值,如下所示:
case 3: //Cash Withdrawal
printf("You are about to withdraw cash from an account.\n \n");
withdrawnAmount = withdrawal(balance); //Calling function to withdraw money from existing account
if(withdrawnAmount > 0)
balance -= withdrawnAmount;
else
printf("-1");
printf("Your new account balance is $%d\n\n", balance);
break;
希望能帮助到你。
推荐阅读
- postgresql - 在 plsql - postgresql 中创建对象列表
- react-native - 在 react-navigation v3 中默认情况下,标题后退按钮不起作用
- javascript - 使用javascript在数组中添加元素的值而不使用const
- python - 将文本添加到轴间箭头
- c# - 如何复制与其他表(相关)中链接的数据的行并将它们作为新记录插入 - Linq C#
- python - 我们可以在垂直边缘检测图像中找到两个垂直边缘之间的关系/函数吗?
- c# - 如何在使用“SpecifiedPickupDirectory”作为传递方法发送电子邮件时在 AWS 上创建电子邮件文件
- php - 如何为这样的一对一关系建立雄辩的关系
- microcontroller - PIC uc 编程没有 MCLR 引脚
- node.js - Mongoose:使用其他模型的模式