如何定位循环,将添加用户输入并显示输入?

时间:2016-10-24 21:03:55

标签: c#

  class Program
    {
        static void Main(string[] args)
        {
            int sum = 0;
            int count = 0;

            Console.WriteLine("Please enter all the numbers you would like to add. When finished, enter -1");

            string numbers = Console.ReadLine();

            while (numbers != "-1")
            {
                sum += int.Parse(numbers);
                count++;
                Console.WriteLine(sum);
                numbers = Console.ReadLine();

            }

        }
    }

当我运行它时,它会立即添加数字。我需要它,所以当用户键入-1时,我也不能将它关闭。任何帮助都会很感激。

1 个答案:

答案 0 :(得分:-1)

你走了:

public class Program
{
    public static void Main(string[] args)
    {
        int sum = 0;
        int count = 0;
        int num = 0;

        Console.WriteLine("Please enter all the numbers you would like to add. When finished, enter -1");

        do 
        {
            string buffer = Console.ReadLine();

            if (Int32.TryParse(buffer, out num) && num != -1)
            {
                sum += num;
                count++;
                Console.WriteLine(String.Format("Entered: [{0}], Running total over [{1}] numbers is: [{2}].", num, count, sum));
            }
        }
        while (num != -1);
    }
}