0

我是 C# 和强类型语言的新手。我正在为大学做作业,我的程序现在按预期工作。但是,我更改了 2 个静态 void 方法标题以使返回类型没有意识到这样做会导致扣分。

Current method headings
static bool DispenseCash(double amount, int whichAccount, bool validAmount) and
static double WithdrawAmount(int whichAccount) must remain 

What they need to be.
static void DispenseCash(double amount) and
static void WithdrawAmount(int whichAccount)

我更改了它们,因为我不知道如何从
静态 void WithdrawAmount(int whichAccount) 返回可变金额并将其用作静态 void DispenseCash(double amount) 中的参数。

我被迫同时使用这两种方法,而不是使用一种更大的方法来解决问题。

这是我的代码片段,可以更好地解释它。我只包括了相关部分以保持简短。

int whichAccount = int.Parse(Console.ReadLine());
do
{
double amount = WithdrawAmount(whichAccount);
validAmount = DispenseCash(amount, whichAccount, validAmount);
} while (validAmount == false);

//end of relevant method calls in main

static double WithdrawAmount(int whichAccount)    
{
Console.Write("\nPlease enter how much you would like to withdraw: $");
double amount = double.Parse(Console.ReadLine());       
return amount; 
}
//end WithdrawAmount

在随后的 DispenseCash 方法中,如果它是 static void DispenseCash(double amount) 我如何将 int whichAccount 和 bool validAmount 传递给它并从中返回一个 bool validAmount 。

private static bool DispenseCash(double amount, int whichAccount, bool validAmount)
{
int numOf20s;
int numOf50s;
double balenceMinusAmount = (accountBalances[whichAccount]) - Convert.ToInt32(amount); 

if((Convert.ToInt32(amount) >= 1) && (Convert.ToInt32(amount) % 50 == 0) &&   (balenceMinusAmount >= accountLimits[whichAccount]))
{

numOf50s = Convert.ToInt32(amount) / 50;
numOf20s = (Convert.ToInt32(amount) % 50) / 20;


Console.WriteLine("Number of 50's = {0}", numOf50s);
Console.WriteLine("Number of 20's = {0}", numOf20s);
accountBalances[whichAccount] = (accountBalances[whichAccount]) - amount;
return validAmount = true;
}

else
      {
          Console.WriteLine("Invalid entry");
          return validAmount = false;
      }
}

请记住,我根本无法更改方法标题。但我可以在方法中调用其中一个或新方法。我尝试了一些不同的东西,但所有尝试都失败了。

4

1 回答 1

2

正如 jdphenix 所提到的,我不确定为什么要求您这样做。它违背了基本的编程原则。也许我们不了解手头问题的全部背景。

我能想到的唯一方法是在您的应用程序中使用静态变量。

private static double withdrawalAmount;
private static int selectedAccount;
private static bool isValidAmount;

然后在您需要的方法中使用这些,例如:

public static void WithdrawAmount(int whichAccount)
    {
        Console.Write("\nPlease enter how much you would like to withdraw: $");
        withdrawalAmount = double.Parse(Console.ReadLine());
    }
于 2013-09-06T02:03:42.580 回答