0
我很喜歡編程c#的初學者,公式中有兩個變量不能解析爲整數,儘管我將它們聲明爲主函數。我有多個方法實現小任務,它似乎並沒有將主變量鏈接到方法之一,其餘代碼沒有任何錯誤,所以我不知道爲什麼它沒有執行公式。 (我必須張貼所有的代碼,以顯示U)Visual C# - 變量在當前上下文中不存在
public static void Main()
{
int income = 0;
int children = 0;
int tax = 0;
AskForIncome(income);
NoChild(children);
CalculateTax(tax);
ExitProgram();
}
public static void AskForIncome(int income)
{
Console.WriteLine("What is your total income: ");
string testNum = Console.ReadLine();
bool dummyBool = int.TryParse(testNum, out income);
if (dummyBool)
{
Console.WriteLine();
}
else if(income < 0)
{
Console.WriteLine("Your income cannot be negative.");
}
else
{
Console.WriteLine("Enter your income as a whole-dollar numeric figure.");
}
}
public static void NoChild(int children)
{
Console.WriteLine("How many children do you have: ");
string testChild = Console.ReadLine();
bool dummyBool2 = int.TryParse(testChild, out children);
if (dummyBool2)
{
Console.WriteLine();
}
else if(children < 0)
{
Console.WriteLine("You must enter a positive number.");
}
else
{
Console.WriteLine("You must enter a valid number.");
}
}
public static void CalculateTax(int tax)
{
tax = income - 10000 - (children * 2000);
if (tax < 0)
{
Console.WriteLine("You owe no tax.");
}
else
{
Console.WriteLine("You owe a total of $" + tax + " tax.");
}
}
由於int是值類型,因此您所做的是通過值傳遞,因此這些更改在主方法中不可見。有關此概念的詳細信息,請參閱https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value。 – Smit
在c#中,您需要使用'AskForIncome(ref int income)'來傳遞參考。 – Smit