我的计算器不能使用c#控制台应用程序

本文关键字:控制台 应用程序 计算器 不能 我的 | 更新日期: 2023-09-27 18:13:41

这可能是一个非常简单的解决方案,但是当它给出3个错误消息时:

The name 'iNum1' does not exist in the current context  
The name 'iNum2' does not exist in the current context  
The name 'soOper' does not exist in the current context 

当我删除最后一行代码时,它可以工作,但没有它我就无法计算它。我希望有人能帮忙。代码如下:

//information
    Console.WriteLine("This is a calculator");
    //Let them fill in the first number
    Console.WriteLine("Please enter the first number");
    bool bNoNum1 = true;
    while (bNoNum1)
    {
        string sNum1 = Console.ReadLine();
        try
        {
            int iNum1 = int.Parse(sNum1);
            bNoNum1 = false;
        }
        catch (Exception)
        {
            Console.WriteLine("That's not a number");
        }
    }

    //Let them fill in (*, +, / of -)
    Console.WriteLine("Please enter +, +, - or :");
    bool bNoOperator = true;

    do
    {
        string sOper = Console.ReadLine();
        if (sOper == "x")
        {
            string soOper = "*";
            bNoOperator = false;
        }
        else if (sOper == ":")
        {
            string soOper = "/";
            bNoOperator = false;
        }
        else if (sOper == "+")
        {
            string soOper = "+";
            bNoOperator = false;
        }
        else if (sOper == "-")
        {
            string soOper = "-";
            bNoOperator = false;
        }
        else
        {
            Console.WriteLine("De operator " + sOper + " Is niet bekend. Kies uit +, -, x of :");
        }
    } while (bNoOperator);

    //Enter second number
    Console.WriteLine("Please enter the second number");
    bool bNoNum2 = true;
    while (bNoNum2)
    {
        string sNum2 = Console.ReadLine();
        try
        {
            int iNum2 = int.Parse(sNum2);
            bNoNum2 = false;
        }
        catch (Exception)
        {
            Console.WriteLine("That's not a number");
        }
    }
    //calculating
    int uitkomst = iNum1 + soOper + iNum2;

我的计算器不能使用c#控制台应用程序

你需要将这三个变量声明为全局变量在你的上下文之外,把这些变量放在"像这样,

Console.WriteLine("This is a calculator");
"
int iNum1;
int iNum2;
string sOper = "";

您在错误的位置声明了iNum1和iNum2 -在一些内括号内。它们在最后一行所在的范围内是未知的。在不同的级别声明这些变量。

在任何情况下,当你这样做,你会有另一个问题:soper是一个字符串。