//面向过程计算器
//思路: 需要注意的是: 两个数相除 除数不能为0;
//1、提示用户输入
//2、进行运算
//3、得到结果
Console.WriteLine("请输入第一个数字: ");
double firstNumber = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("请输入第二个数字: ");
double secondNumber = Convert.ToDouble(Console.ReadLine());
//提示输入运算符
string oper = Console.ReadLine();
//声明一个用于存储结果的变量
//double sum = 0;
//可空类型
double? sum = null;
//异常的处理: 除数不能为零
try
{
//用switch case进行多条件的定值的判断
switch (oper)
{
case "+": sum = firstNumber + secondNumber;
break;
case "-": sum = firstNumber - secondNumber;
break;
case "*": sum = firstNumber * secondNumber;
break;
case "/": sum = firstNumber / secondNumber;
if (secondNumber == 0)
{
throw new Exception("除数不能为 0");
}
break;
default:
Console.WriteLine("您输入的不是一个数字,请按任意键结束...");
Console.ReadKey();
return; //结束
}
if (sum != null)
//输出结果
Console.WriteLine("{0}{1}{2} = {3}", firstNumber, oper, secondNumber, sum);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message); //上面的异常写的是什么,此地方的Message的内容就是什么
}
Console.ReadKey();
///////////////////////////////////////////////////////////
改成用方法的方式
static void Main(string[] args)
{
//输入数字
double firstNumber = ReadDouble();
double secondNumber = ReadDouble();
Console.WriteLine("请输入运算符: ");
string oper = Console.ReadLine();
//开始计算
//要异常进行处理: 除数不能为0,运算符的符号不正确
try
{
double dResult = Calculation(firstNumber, secondNumber, oper);
Console.WriteLine("{0} {1} {2} = {3}", firstNumber, oper, secondNumber, dResult);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
/// <summary>
/// 判断输入的内容
/// </summary>
/// <returns></returns>
public static double ReadDouble()
{
double dNmber;
while (true)
{
Console.WriteLine("请输入第一个数字: ");
string input = Console.ReadLine();
//把用户输入的内容转城字符串
if (double.TryParse(input, out dNmber))
{
break;
}
else
{
Console.WriteLine("对不起, 您输入的不是一个数字,请重新输入...");
}
}
return dNmber;
}
/// <summary>
/// 计算的方法
/// </summary>
/// <param name="firstNumber"></param>
/// <param name="secondNumber"></param>
/// <param name="oper"></param>
/// <returns></returns>
public static double Calculation(double firstNumber, double secondNumber, string oper)
{
double sum;
//用switch case进行多条件的定值的判断
switch (oper)
{
case "+": sum = firstNumber + secondNumber;
break;
case "-": sum = firstNumber - secondNumber;
break;
case "*": sum = firstNumber * secondNumber;
break;
case "/":
//在代码运行的过程中,实际条件与预期条件可能不一致的时候,可以抛个异常
if (secondNumber == 0)
{
throw new Exception("除数不能为 0");
}
sum = firstNumber / secondNumber;
break;
default:
throw new Exception("请输入正确的运算符...");
}
return sum;
}
来源:https://www.cnblogs.com/zsongs/p/5074788.html