You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何将循环的数字哨兵值替换为单词Quit实现程序终止?

解决方案

你直接替换报错的核心原因是原有逻辑会直接将所有用户输入强制转换为int类型,而字符串"Quit"无法被转换为整数,不需要设置特殊参数,只要调整输入的读取和判断顺序即可,修改逻辑如下:

  • 先以字符串格式读取用户输入,不要直接转int
  • 优先判断输入内容是否为哨兵值"Quit",匹配成功直接终止循环
  • 若不是哨兵值,再尝试将输入转换为int类型,建议用int.TryParse做合法性校验,避免用户输入其他非数字内容导致程序崩溃

修改后的完整代码如下:

using System;

class Program {
  public static void Main (string[] args) {
    int sum = 0;
    int counter = 0; 
    int max = Int32.MinValue;
    int min = Int32.MaxValue;
    bool keepGoing = true; 
    while(keepGoing) {
      Console.WriteLine("Please enter a number or enter Quit to stop the program:");
      // 先读取为字符串
      string input = Console.ReadLine();
      // 先判断是不是哨兵值,这里加了忽略大小写的配置,输入quit/Quit都能识别,不需要可以删掉StringComparison参数
      if (input.Equals("Quit", StringComparison.OrdinalIgnoreCase))
      {
        keepGoing = false;
      }
      else
      {
        // 校验输入是不是合法数字
        if (int.TryParse(input, out int number))
        {
          counter++;
          sum += number;
          if (number >= max) {
            max = number;
          }
          if (number <= min) {
            min = number;
          }
        }
        else
        {
          // 非数字非Quit的输入给出提示
          Console.WriteLine("输入不合法,请输入数字或者Quit退出程序");
        }
      }
    }
    // 加边界判断,避免没有输入数字的时候除零报错
    if (counter > 0)
    {
      double average = (double) sum / counter;
      Console.WriteLine($"{counter} numbers were entered.");
      Console.WriteLine("The average is:"  + average);
      Console.WriteLine("The sum is:"  + sum);
      Console.WriteLine("The maximum value is:"  + max);
      Console.WriteLine("The minimum value is:"  + min);
    }
    else
    {
      Console.WriteLine("未输入任何有效数字");
    }
  }
}

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 18:15:05