簡體   English   中英

我的計算器無法使用C#控制台應用程序

[英]My calculator won't work c# console application

它可能是一個非常簡單的解決方案,但是當它給出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;

您需要將這3個變量聲明為上下文之外的全局變量,將這些變量放在“

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

您在錯誤的位置(在某些內部括號內)聲明了iNum1和iNum2。 在最后一行所在的范圍內,它們是未知的。 在不同級別上聲明這些變量。

無論如何,您都會遇到另一個問題:soOper是一個字符串。 您正在使用一個字符串和另一個int添加一個int。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM