无法使用Sentinel Value退出C#应用程序

时间:2014-02-25 19:27:08

标签: c# visual-studio-2012

我创建的应用程序允许用户输入数字,这些数字提供输入数字的平均值。用户将被允许输入他们选择的数量。每次输入后,我都会显示当前的平均值。

我无法退出该应用程序。我需要帮助才能在代码中找到一些问题。

以下代码现已更正:

 string input = "";
 double noentered = 0;
 double total=0;
 double average = 0;
 do
 {
Console.Write("enter a number or Q to quit",input);   
input = Console.ReadLine();
if (input != "q" && input != "Q") 
{
 noentered++;
 total +=  Convert.ToInt32(input);
 average = total / noentered;
 Console.WriteLine(" Total: {0} \t Number Entered: {1} \t Average:{2}", total, noentered,average);
}
}
 }while (input != "q" && input != "Q");

2 个答案:

答案 0 :(得分:1)

在尝试将输入转换为int之前,移动if-sentence来检查输入:

        string input = "";
        double noentered = 0;
        double total = 0;
        double average = 0;
        do
        {
            {
                Console.Write("enter a number or Q to quit", input);
                input = Console.ReadLine();
                if (input != "q" && input != "Q")
                {
                    total += Convert.ToInt32(input);
                    average = total / noentered;
                    noentered++;
                    Console.WriteLine(" Total: {0} \t Number Entered: {1} \t Average:{2}", total, noentered, average);
                }


            }
        } while (input != "q" && input != "Q");

答案 1 :(得分:1)

      do
        {
            Console.Write("enter a number or Q to quit", input);
            input = Console.ReadLine();
            if (input != "q" && input != "Q")
            {
                noentered++;
                total += Convert.ToInt32(input);
                average = total / noentered;
                Console.WriteLine(" Total: {0} \t Number Entered: {1} \t Average:{2}", total, noentered, average);
            }
        } while (input != "q" && input != "Q");

这很有效。请注意if条件的位置。读取后检查输入的值。在您的代码中,一次通过后检查该值。此外,您可能希望在计算平均值之前增加计数以获得准确的平均值。