如何哨兵循环,将添加用户输入并显示输入

本文关键字:输入 添加 用户 显示 循环 何哨兵 哨兵 | 更新日期: 2023-09-27 18:14:37

  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时我不能让它关闭。

如何哨兵循环,将添加用户输入并显示输入

给你:

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);
    }
}