如果尝试将数字除以零,控制台应用可能会冻结,然后在代码编辑器中显示错误。
有时,应用不会冻结且调试器不会显示“被零除”错误。 相反,应用可能会返回意外的非数值结果,例如无穷大符号。 以下代码修复仍适用。
让我们更改代码来处理此错误。 在 Program.cs中,将 case "d":
的代码替换为以下代码:
// Ask the user to enter a non-zero divisor until they do so.
while (num2 == 0)
Console.WriteLine("Enter a non-zero divisor: ");
num2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2));
break;
替换代码后,包含 switch
语句的部分看起来应与下图类似:
现在,当你将任意数字除以零时,应用会要求另一个数字,并不断询问,直到你提供非零数。
如果在程序需要数字字符时输入了字母字符,程序将会冻结。 Visual Studio 指出代码编辑器中的错误。
你可以将应用划分为两个类:Calculator
和 Program
,而不是依赖 program
类来处理所有代码。
Calculator
类处理大部分计算工作,Program
类处理用户界面和错误处理工作。
让我们开始吧。
在 Program.cs中,删除所有内容并添加以下新 Calculator
类:
class Calculator
public static double DoOperation(double num1, double num2, string op)
double result = double.NaN; // Default value is "not-a-number" if an operation, such as division, could result in an error.
// Use a switch statement to do the math.
switch (op)
case "a":
result = num1 + num2;
break;
case "s":
result = num1 - num2;
break;
case "m":
result = num1 * num2;
break;
case "d":
// Ask the user to enter a non-zero divisor.
if (num2 != 0)
result = num1 / num2;
break;
// Return text for an incorrect option entry.
default:
break;
return result;
另请添加新 Program
类,如下所示:
class Program
static void Main(string[] args)
bool endApp = false;
// Display title as the C# console calculator app.
Console.WriteLine("Console Calculator in C#\r");
Console.WriteLine("------------------------\n");
while (!endApp)
// Declare variables and set to empty.
string numInput1 = "";
string numInput2 = "";
double result = 0;
// Ask the user to type the first number.
Console.Write("Type a number, and then press Enter: ");
numInput1 = Console.ReadLine();
double cleanNum1 = 0;
while (!double.TryParse(numInput1, out cleanNum1))
Console.Write("This is not valid input. Please enter a numeric value: ");
numInput1 = Console.ReadLine();
// Ask the user to type the second number.
Console.Write("Type another number, and then press Enter: ");
numInput2 = Console.ReadLine();
double cleanNum2 = 0;
while (!double.TryParse(numInput2, out cleanNum2))
Console.Write("This is not valid input. Please enter a numeric value: ");
numInput2 = Console.ReadLine();
// Ask the user to choose an operator.
Console.WriteLine("Choose an operator from the following list:");
Console.WriteLine("\ta - Add");
Console.WriteLine("\ts - Subtract");
Console.WriteLine("\tm - Multiply");
Console.WriteLine("\td - Divide");
Console.Write("Your option? ");
string op = Console.ReadLine();
result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
if (double.IsNaN(result))
Console.WriteLine("This operation will result in a mathematical error.\n");
else Console.WriteLine("Your result: {0:0.##}\n", result);
catch (Exception e)
Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
Console.WriteLine("------------------------\n");
// Wait for the user to respond before closing.
Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
if (Console.ReadLine() == "n") endApp = true;
Console.WriteLine("\n"); // Friendly linespacing.
return;
选择 计算器 按钮或按 F5 运行应用。
按照提示操作,将数字 42 除以数字 119。 结果应类似于以下屏幕截图:
现在可以运行更多计算,直到选择关闭控制台应用。 结果中的小数位数也更少。 如果输入的字符不正确,则会收到相应的错误响应。
你可以将应用划分为两个类:Calculator
和 Program
,而不是依赖 program
类来处理所有代码。
Calculator
类处理大部分计算工作,Program
类处理用户界面和错误处理工作。
让我们开始吧。
在 Program.cs中,删除所有内容并添加以下新 Calculator
类:
class Calculator
public static double DoOperation(double num1, double num2, string op)
double result = double.NaN; // Default value is "not-a-number" if an operation, such as division, could result in an error.
// Use a switch statement to do the math.
switch (op)
case "a":
result = num1 + num2;
break;
case "s":
result = num1 - num2;
break;
case "m":
result = num1 * num2;
break;
case "d":
// Ask the user to enter a non-zero divisor.
if (num2 != 0)
result = num1 / num2;
break;
// Return text for an incorrect option entry.
default:
break;
return result;
另请添加新 Program
类,如下所示:
class Program
static void Main(string[] args)
bool endApp = false;
// Display title as the C# console calculator app.
Console.WriteLine("Console Calculator in C#\r");
Console.WriteLine("------------------------\n");
while (!endApp)
// Declare variables and set to empty.
// Use Nullable types (with ?) to match type of System.Console.ReadLine
string? numInput1 = "";
string? numInput2 = "";
double result = 0;
// Ask the user to type the first number.
Console.Write("Type a number, and then press Enter: ");
numInput1 = Console.ReadLine();
double cleanNum1 = 0;
while (!double.TryParse(numInput1, out cleanNum1))
Console.Write("This is not valid input. Please enter a numeric value: ");
numInput1 = Console.ReadLine();
// Ask the user to type the second number.
Console.Write("Type another number, and then press Enter: ");
numInput2 = Console.ReadLine();
double cleanNum2 = 0;
while (!double.TryParse(numInput2, out cleanNum2))
Console.Write("This is not valid input. Please enter a numeric value: ");
numInput2 = Console.ReadLine();
// Ask the user to choose an operator.
Console.WriteLine("Choose an operator from the following list:");
Console.WriteLine("\ta - Add");
Console.WriteLine("\ts - Subtract");
Console.WriteLine("\tm - Multiply");
Console.WriteLine("\td - Divide");
Console.Write("Your option? ");
string? op = Console.ReadLine();
// Validate input is not null, and matches the pattern
if (op == null || ! Regex.IsMatch(op, "[a|s|m|d]"))
Console.WriteLine("Error: Unrecognized input.");
result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
if (double.IsNaN(result))
Console.WriteLine("This operation will result in a mathematical error.\n");
else Console.WriteLine("Your result: {0:0.##}\n", result);
catch (Exception e)
Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
Console.WriteLine("------------------------\n");
// Wait for the user to respond before closing.
Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
if (Console.ReadLine() == "n") endApp = true;
Console.WriteLine("\n"); // Friendly linespacing.
return;
最好对输入字符串使用可为空的类型(带有 ?
符号),因为 System.Console.ReadLine
返回 可为空的引用类型。
选择 计算器 按钮或按 F5 运行应用。
按照提示操作,将数字 42 除以数字 119。 结果应类似于以下屏幕截图:
现在可以运行更多计算,直到选择关闭控制台应用。 结果中的小数位数也更少。 如果输入的字符不正确,则会收到相应的错误响应。
如果尚未这样做,请关闭计算器应用。
关闭 Visual Studio 中的 输出 窗格。
在 Visual Studio 中,按 Ctrl +S 保存应用。
添加 Git 源代码管理
有了应用程序后,你可能想要将其添加到 Git 存储库。 借助 Visual Studio,可以使用可直接从 IDE 使用的 Git 工具轻松完成此过程。
Git 是最常用的新式版本控制系统。 无论你是专业开发人员还是学习如何编写代码,Git 都非常有用。 如果你不熟悉 Git,https://git-scm.com/
网站是一个很好的起点。 你可以找到备忘单、热门在线书籍和 Git 基本信息视频。
若要将代码与 Git 相关联,请先创建代码所在的新 Git 存储库:
在 Visual Studio 右下角的状态栏中,选择 添加到源代码管理,然后选择 Git。
在 “创建 Git 存储库”对话框中,登录到 GitHub:
存储库名称根据文件夹位置自动填充。 默认情况下,新存储库是专用的,这意味着你是唯一可以访问它的人。
无论存储库是公共的还是专用的,最好有一个安全存储在 GitHub 上的代码的远程备份。 即使你未与团队合作,远程存储库也会让你从任何计算机获得代码。
选择“创建并推送”。 创建存储库后,可在状态栏中看到状态详细信息:
下面是 Visual Studio 状态栏中提供的 Git 操作的简要摘要:
向上/向下箭头显示当前分支中的传出/传入提交数。 可以使用此图标来拉取任何传入提交或推送任何传出提交。
若要查看特定提交,请选择向上/向下箭头,然后选择“查看传出/传入”。
铅笔显示代码的未提交更改数。 可以选择此图标,在 Git 更改 窗口中查看这些更改。
Git 菜单为文件上的存储库操作提供了工具。 在 Visual Studio中使用 git fetch、pull、push 和 sync 进行版本控制。
有关如何将 Git 与应用配合使用的详细信息,请参阅 Visual Studio 中的关于 Git。
审阅:代码已完成
在本教程中,你对计算器应用进行了许多更改。 应用现在更有效地处理计算资源,并处理大多数用户输入错误。
下面是完整的代码,全部放在一个位置:
class Calculator
public static double DoOperation(double num1, double num2, string op)
double result = double.NaN; // Default value is "not-a-number" which we use if an operation, such as division, could result in an error.
// Use a switch statement to do the math.
switch (op)
case "a":
result = num1 + num2;
break;
case "s":
result = num1 - num2;
break;
case "m":
result = num1 * num2;
break;
case "d":
// Ask the user to enter a non-zero divisor.
if (num2 != 0)
result = num1 / num2;
break;
// Return text for an incorrect option entry.
default:
break;
return result;
class Program
static void Main(string[] args)
bool endApp = false;
// Display title as the C# console calculator app.
Console.WriteLine("Console Calculator in C#\r");
Console.WriteLine("------------------------\n");
while (!endApp)
// Declare variables and set to empty.
string numInput1 = "";
string numInput2 = "";
double result = 0;
// Ask the user to type the first number.
Console.Write("Type a number, and then press Enter: ");
numInput1 = Console.ReadLine();
double cleanNum1 = 0;
while (!double.TryParse(numInput1, out cleanNum1))
Console.Write("This is not valid input. Please enter a numeric value: ");
numInput1 = Console.ReadLine();
// Ask the user to type the second number.
Console.Write("Type another number, and then press Enter: ");
numInput2 = Console.ReadLine();
double cleanNum2 = 0;
while (!double.TryParse(numInput2, out cleanNum2))
Console.Write("This is not valid input. Please enter a numeric value: ");
numInput2 = Console.ReadLine();
// Ask the user to choose an operator.
Console.WriteLine("Choose an operator from the following list:");
Console.WriteLine("\ta - Add");
Console.WriteLine("\ts - Subtract");
Console.WriteLine("\tm - Multiply");
Console.WriteLine("\td - Divide");
Console.Write("Your option? ");
string op = Console.ReadLine();
result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
if (double.IsNaN(result))
Console.WriteLine("This operation will result in a mathematical error.\n");
else Console.WriteLine("Your result: {0:0.##}\n", result);
catch (Exception e)
Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
Console.WriteLine("------------------------\n");
// Wait for the user to respond before closing.
Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
if (Console.ReadLine() == "n") endApp = true;
Console.WriteLine("\n"); // Friendly linespacing.
return;
public static double DoOperation(double num1, double num2, string op)
double result = double.NaN; // Default value is "not-a-number" which we use if an operation, such as division, could result in an error.
// Use a switch statement to do the math.
switch (op)
case "a":
result = num1 + num2;
break;
case "s":
result = num1 - num2;
break;
case "m":
result = num1 * num2;
break;
case "d":
// Ask the user to enter a non-zero divisor.
if (num2 != 0)
result = num1 / num2;
break;
// Return text for an incorrect option entry.
default:
break;
return result;
class Program
static void Main(string[] args)
bool endApp = false;
// Display title as the C# console calculator app.
Console.WriteLine("Console Calculator in C#\r");
Console.WriteLine("------------------------\n");
while (!endApp)
// Declare variables and set to empty.
// Use Nullable types (with ?) to match type of System.Console.ReadLine
string? numInput1 = "";
string? numInput2 = "";
double result = 0;
// Ask the user to type the first number.
Console.Write("Type a number, and then press Enter: ");
numInput1 = Console.ReadLine();
double cleanNum1 = 0;
while (!double.TryParse(numInput1, out cleanNum1))
Console.Write("This is not valid input. Please enter a numeric value: ");
numInput1 = Console.ReadLine();
// Ask the user to type the second number.
Console.Write("Type another number, and then press Enter: ");
numInput2 = Console.ReadLine();
double cleanNum2 = 0;
while (!double.TryParse(numInput2, out cleanNum2))
Console.Write("This is not valid input. Please enter a numeric value: ");
numInput2 = Console.ReadLine();
// Ask the user to choose an operator.
Console.WriteLine("Choose an operator from the following list:");
Console.WriteLine("\ta - Add");
Console.WriteLine("\ts - Subtract");
Console.WriteLine("\tm - Multiply");
Console.WriteLine("\td - Divide");
Console.Write("Your option? ");
string? op = Console.ReadLine();
// Validate input is not null, and matches the pattern
if (op == null || ! Regex.IsMatch(op, "[a|s|m|d]"))
Console.WriteLine("Error: Unrecognized input.");
result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
if (double.IsNaN(result))
Console.WriteLine("This operation will result in a mathematical error.\n");
else Console.WriteLine("Your result: {0:0.##}\n", result);
catch (Exception e)
Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
Console.WriteLine("------------------------\n");
// Wait for the user to respond before closing.
Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
if (Console.ReadLine() == "n") endApp = true;
Console.WriteLine("\n"); // Friendly linespacing.
return;
继续学习本教程的第二部分:
第 2 部分:扩展和调试 C# 控制台应用