我正在尝试用C#制作一个简单的计算器。但由于某种原因,程序无法识别2个变量。这是代码的第52行:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter your first number: ");
string num1 = Console.ReadLine();
//Convert the string to a integer and check if it contains a number
try
{
int number1 = Convert.ToInt32(num1);
}
catch (FormatException e)
{
Console.WriteLine("That was not a number!");
}
catch (OverflowException e)
{
Console.WriteLine("Wow, not so many numbers..");
}
Console.WriteLine("Press / * + or -: ");
string symbol = Console.ReadLine();
Console.WriteLine("Enter your second number: ");
String num2 = Console.ReadLine();
//Convert the string to a integer and check if it contains a number
try
{
int number2 = Convert.ToInt32(num2);
}
catch(FormatException e)
{
Console.WriteLine("That was not a number!");
}
catch(OverflowException e)
{
Console.WriteLine("'Wow, not so many numbers..");
}
//check the symbol
if(symbol == "+")
{
long result = AddNumber(number1, number2);
}
else if (symbol == "-")
{
}
}
//functions
public int AddNumber(int number1, int number2)
{
int result = number1 + number2;
return result;
}
public int SubstractNumber(int number1, int number2)
{
int result = number1 - number2;
return result;
}
public int DevideNumber(int number1, int number2)
{
int result = number1 / number2;
return result;
}
public int MultiNumber(int number1, int number2)
{
int result = number1 * number2;
return result;
}
}
}
并在第18行和第37行宣布。
答案 0 :(得分:6)
这是合理的,因为两个变量都是声明的try块中的本地变量。你必须在它们当前被声明的try
块之外声明它们,以便在第52行“可见”。你可以这样做:
static void Main(string[] args)
{
int number1;
int number2;
// ....
try
{
number1 = Convert.ToInt32(num1);
}
// ...
try
{
number2 = Convert.ToInt32(num1);
}
// ...
}