[刷题] A+B问题
题目描述 Description
输入两个整数A和B,输出他们的和
输入描述 Input Description
输入为一行,包含两个整数A,B。数据保证A与B都在0 ~ 100的范围内
输出描述 Output Description
输入A与B的和,数据保证A与B的和在0 ~ 100的范围内
样例输入 Sample Input
1 3
样例输出 Sample Output
4
数据范围及提示 Data Size & Hint
无
结题思路
1 保证输入字符串正确
2 保证不超出范围
代码
1 using System; 2 3 namespace ABSum 4 { 5 internal class Program 6 { 7 private static void Main(string[] args) 8 { 9 string hint = "请输入整数A和B, A和B之前使用空格分割..."; 10 string input; 11 12 Console.WriteLine(hint); 13 while ((input = Console.ReadLine()) != null) 14 { 15 string mergeStr = MergeSpace(input.Trim()); // 清理两头的空格 并把中间连续的空格合并为一个空格 16 string[] pars = mergeStr.Split(' ');// 获取 A 和 B 的值 17 18 if (pars.Length != 2) 19 { 20 Console.WriteLine("Error:请正确输入A和B的值"); 21 Console.WriteLine(hint); 22 continue; 23 } 24 try 25 { 26 int a = Convert.ToInt32(pars[0]); 27 int b = Convert.ToInt32(pars[1]); 28 29 if (a < 0 || a > 100) 30 { 31 Console.WriteLine("Error:A 只能在 0 到100 之间"); 32 Console.WriteLine(hint); 33 continue; 34 } 35 36 if (b < 0 || b > 100) 37 { 38 Console.WriteLine("Error:B 只能在 0 到100 之间"); 39 Console.WriteLine(hint); 40 continue; 41 } 42 43 Console.WriteLine(Sum(a, b)); 44 } 45 catch (Exception) 46 { 47 Console.WriteLine("Error:只能输入整数"); 48 } 49 50 Console.WriteLine(hint); 51 } 52 } 53 54 /// <summary> 55 /// 合并多个的连续空格. 56 /// </summary> 57 /// <param name="str">字符串</param> 58 /// <returns></returns> 59 /// <exception cref="ArgumentNullException">str</exception> 60 private static string MergeSpace(string str) 61 { 62 if (string.IsNullOrEmpty(str)) 63 { 64 throw new ArgumentNullException(nameof(str)); 65 } 66 67 return new System.Text.RegularExpressions.Regex("[\\s]+").Replace(str, " "); 68 } 69 70 private static int Sum(int a, int b) 71 { 72 return a + b; 73 } 74 } 75 }
浙公网安备 33010602011771号