日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

C# 实现ReadInt()直接输入数字的函数 含有检错功能

發布時間:2024/2/28 C# 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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()直接输入数字的函数 含有检错功能的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。