【问题标题】:Variable scope trought If /else if block变量范围 trought If /else if 块
【发布时间】:2017-01-18 09:20:39
【问题描述】:

我有问题。我写了一个控制台应用程序来练习。程序反复要求用户输入一个数字,程序将这些数字相加,当用户输入“完成”时,程序将总数除以输入的数字。

所以我的问题是。该程序不会遵守,因为如您所见,我必须声明 int convert = int.Parse(input);进入 else 子句,因为如果用户键入数字,程序将跳过前 2 个选项并将字符串转换为数字,程序继续按原样进行,但是因为我声明将 int 转换为 else,所以在 else 中转换如果,不存在。

我知道由于变量范围,我必须将所有内容放在同一个括号中,但是如何?

bool keepGoing = true;
int total = 0;

//The loop begins, repeatedly asks the user for  numbers.
while (true)
{

     //Asks the user for numbers .
    Console.Write("Type a number:");
    string input = Console.ReadLine();

    // When user types in quit the program quits
    if (input == "quit")
    {
        break;
    }


    // When user types "done", dividing total with converted(entered numbers).
    else if (input == "done")
    {
         total /= converted;
        Console.WriteLine(total);
        continue;
    }

    // If user types a number, convert into integer and add total and converted together.
    else
    {
        try
        {
            int converted = int.Parse(input);
            total += converted;
            Console.WriteLine(total);             
        }

        // Tells the user to type again.
        catch (FormatException)
        {
            Console.WriteLine("Invalid Input, please type again");
        }
    }
}

【问题讨论】:

  • 程序将总数除以输入的数字 您的程序似乎并没有按照您的想法去做。最多将总数除以 last 输入的数字。这是预期的行为吗?
  • 是的,你是对的,我刚刚意识到我的错误 :) 我应该记录输入的数字,对吗?我的意思是创建另一个变量并在每次用户输入数字时给出+1,然后将其除以总数?
  • 对我来说听起来很合理:)

标签: c# scope


【解决方案1】:

这里给出的完整代码块 ->

    int total = 0;
    int converted = 0;

    //The loop begins, repeatedly asks the user for  numbers.
    while (true)
    {

        //Asks the user for numbers .
        Console.Write("Type a number:");
        string input = Console.ReadLine();

        // When user types in quit the program quits
        if (input == "quit")
        {
            break;
        }


        // When user types "done", dividing total with converted(entered numbers).
        else if (input == "done")
        {
            total /= converted;
            Console.WriteLine(total);
            continue;
        }

        // If user types a number, convert into integer and add total and converted together.
        else
        {
            try
            {
                converted = int.Parse(input);
                total += converted;
                Console.WriteLine(total);
            }

            // Tells the user to type again.
            catch (FormatException)
            {
                Console.WriteLine("Invalid Input, please type again");
            }
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    相关资源
    最近更新 更多