翻譯|使用教程|編輯:陳津勇|2019-11-19 11:53:12.500|閱讀 1067 次
概述:在本C#教程中,您將使用Visual Studio創建和運行控制臺應用程序,并在此過程中探索Visual Studio集成開發環境(IDE)的某些功能。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
在上篇中,介紹了使用VS 2019創建一個簡單的控制臺應用程序、探索整數數學、添加代碼創建計算器等內容。本文承接上文內容,繼續為大家介紹使用VS 2019創建一個簡單的C#控制臺應用程序的其他步驟。
向計算器添加功能
通過調整代碼來添加更多功能。
加小數
計算器應用程序當前接受并返回整數。但是,如果我們添加允許使用小數的代碼,它將更加精確。
如下面的屏幕截圖所示,如果您運行應用程序,然后將數字42除以119,則結果為0(零),這是不正確的。
簡單修改代碼就可以處理小數:
1按Ctrl + F打開“Find and Replace”控件。
2、將int變量的每個實例更改為float。
確保在“Find and Replace”控件中切換“Match case (Alt+C)”和“Match whole word (Alt+W) ” 。
3、再次運行計算器應用,然后將數字42除以119。
請注意,應用程序現在返回的是十進制數字而不是零。
但是,該應用程序僅產生十進制結果?,F在,繼續對代碼進行一些調整,讓應用程序也可以計算小數。
1、使用“Find and Replace”控件(Ctrl + F)將float變量的每個實例更改為double,并將Convert.ToInt32方法的每個實例更改為Convert.ToDouble。
2、運行計算器應用,然后將數字42.5除以119.75。
請注意,該應用程序現在接受十進制值,并返回一個較長的十進制數字作為結果。
調試應用
我們在基本的計算器應用程序上進行了改進,但尚未設置故障保險柜來處理諸如用戶輸入錯誤之類的異常。
例如,如果您試圖將一個數字除以0,或者在應用程序需要一個數字字符時輸入一個alpha字符(反之亦然),應用程序將停止工作并返回一個錯誤。
接下來,我們瀏覽幾個常見的用戶輸入錯誤,在調試器中找到它們,并在代碼中修復錯誤。
修復“被零除”錯誤
當您嘗試將數字除以零時,控制臺應用程序將停止運行。然后,Visual Studio會提示代碼編輯器中的問題。
要處理此錯誤,只需更改幾個代碼:
1、刪除直接出現在的代碼case "d":和注釋之間的代碼// Wait for the user to respond before closing。
2、將其替換為以下代碼:
// 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.ToInt32(Console.ReadLine()); } Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2)); break; }
添加代碼后,帶有switch語句的部分應類似于以下屏幕截圖:
現在,當您將任何數字除以零時,應用程序將提示您換一個數字,直到您提供非零的數字。
修復“格式”錯誤
如果在應用程序要求輸入數字字符時輸入字母字符(反之亦然),則控制臺應用程序將停止運行。然后,Visual Studio會提示代碼編輯器中的問題。
要解決此錯誤,必須重構我們先前輸入的代碼。
修改代碼
我們將應用分為兩類:Calculator和Program,而不是依賴程序類來處理所有代碼。
Calculator類將處理大量的計算工作,而所述Program類將處理用戶界面和捕獲錯誤的工作。
1、刪除以下代碼塊之后的所有內容:
using System; namespace Calculator {
2、添加一個新Calculator類,如下所示:
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; } }
3、然后,添加一個新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 an integer 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 an integer 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(); try { 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; } }
4、選擇Calculator運行程序,或按F5。
5、按照提示將數字42除以119。應用程序應類似于以下屏幕截圖:
請注意,在選擇關閉控制臺應用程序之前,可以選擇輸入更多方程式。并且,我們還減少了結果中的小數位數。
關閉應用程序
1、如果尚未執行此操作,請關閉計算器應用程序。
2、在Visual Studio中關閉“Output”窗格。
3、在Visual Studio中,按Ctrl + S保存應用程序。
4、關閉Visual Studio。
代碼完成
在本教程中,我們對計算器應用程序進行了很多更改。該應用程序現在可以更有效地處理計算資源,并且可以處理大多數用戶輸入錯誤。
以下是涉及的所有代碼:
using System; namespace Calculator { 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 an integer 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 an integer 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(); try { 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; } } }
以上就是本教程的所有內容。下一節,將介紹如何在Visual Studio中使用C#和ASP.NET Core,歡迎持續關注。
想要獲取 Visual Studio 更多資源或正版授權的伙伴請聯系領取
慧都16周年·技術服務月,軟件商城優惠券不限量免費放送,購物立減服務升級,享受折上折>>>
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自: