首页 > 解决方案 > 问题强制从 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;

标签: cfunctiondebuggingreturn

解决方案


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

希望能帮助到你。


推荐阅读