C# 实现ReadInt()直接输入数字的函数 含有检错功能
生活随笔
收集整理的這篇文章主要介紹了
C# 实现ReadInt()直接输入数字的函数 含有检错功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
思路
使用try…catch實現自動檢錯,如果輸入錯誤,提示用戶重新輸入
本函數ReadInt()復制后可以在任何地方使用
輸入輸出(輸入錯誤有反饋,輸入正確無反饋)
變量存儲方式
代碼
代碼一(直接輸入)
using System;namespace 輸入一個數字 {class Program{static void Main(string[] args){Console.WriteLine("請輸入數字");int i;int[] a = new int[10];for (i = 0; i < 10; i++){a[i] = ReadInt();//完美調用}}//ReadInt()輸入數字public static int ReadInt(){int num = 0;while (true){try{num = Convert.ToInt32(Console.ReadLine());return num;}catch{Console.WriteLine("輸入有誤,請重新輸入");}}}} }代碼二(使用了ReadInt)
using System; using System.Collections.Generic; using System.Linq; using System.Text;namespace test {class Program{/// <summary>/// ReadInt()函數定義/// 輸入一個數字,如果格式正確,返回值為此數字。如果輸入錯誤,提示重新輸入/// </summary>/// <returns>返回值為輸入的數字</returns>public static int ReadInt(){int num = 0;while (true){try{num = Convert.ToInt32(Console.ReadLine());return num;}catch{Console.WriteLine("輸入有誤,請重新輸入");}}}static void Main(string[] args){int[] a = new int[1000];int i = 0;//輸入Console.WriteLine("輸入10個值,以回車分隔");//先按照數字分割for(i=0;i<10;i++){a[i] = ReadInt();}//相加int sum = 0;foreach (int iter in a){sum += iter;}//輸出每個數字int j;for (j = 0; j < i; j++){Console.WriteLine(a[j]);}Console.WriteLine("sum={0}", sum);}} }總結
以上是生活随笔為你收集整理的C# 实现ReadInt()直接输入数字的函数 含有检错功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# 房贷计算器(等本降息)
- 下一篇: C# foreach迭代器