【问题标题】:Issue forcing a return -1 from function in C问题强制从 C 中的函数返回 -1
【发布时间】:2018-11-30 02:02:20
【问题描述】:

在初学者的 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 中复制返回

案例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;

【问题讨论】:

  • 强烈建议不要使用图片。请发布实际代码。
  • 抱歉,我试图以正确的格式显示实际代码。
  • 请提供minimal reproducible example 并更好地解释问题。

标签: c function debugging return


【解决方案1】:

我认为在这种情况下,您应该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;

希望对你有帮助。

【讨论】:

  • 谢谢。当我看到您的第一篇文章时,我开始更改主程序以检查返回后的值。非常感谢。
  • 太棒了。将更新我的答案以包括这一点。
  • 添加这个是因为教授在作业中特别声明他想要一个-1返回到这个实例的主程序。否则 { printf("-1\n"); } 休息;
猜你喜欢
  • 1970-01-01
  • 2014-07-25
  • 1970-01-01
  • 2020-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 2020-04-05
相关资源
最近更新 更多