c#不能识别两个变量

本文关键字:两个 变量 不能 识别 | 更新日期: 2023-09-27 18:12:37

我正在尝试用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行声明

c#不能识别两个变量

这是合理的,因为这两个变量都是声明的try块中的局部变量。您必须在当前声明它们的try块之外声明它们,以便在第52行"可见"。你可以这样做:

 static void Main(string[] args)
 {
     int number1;
     int number2;
     // ....
     try
     {
         number1 = Convert.ToInt32(num1);
     }
     // ...
     try
     {
         number2 = Convert.ToInt32(num1);
     }
     // ...
}