代码如下:
using System;
using System.Collections.Generic;
namespace TestProject
{
class Program
{
static void Main(string[] args)
{
int a, b, sum = 0;
var readLine = "";
Console.WriteLine("程序功能:请输入两个数字计算其和(空格分割,回车结束),输入exit结束:");
//将输入的字符串放至readLine变量中,然后判断是否为退出条件 exit
while ((readLine = Console.ReadLine()).ToLower() != "exit")
{
var arr = readLine.Split(new char[] { ' ' });
if (arr.Length != 2)
{
Console.WriteLine("输入不正确,请重新输入!");
continue;
}
//尝试转化输入的两个字符串是否为整数
if (!int.TryParse(arr[0], out a) || !int.TryParse(arr[1], out b))
{
Console.WriteLine("输入的字符串不是整数,请重新输入!");
continue;
}
sum = a + b;
Console.WriteLine("结果:{0} + {1} = {2}", a, b, sum);
a = b = sum = 0;
}
Console.WriteLine("程序结束,按回车结束。");
Console.ReadLine();
}
}
}