楼主:在下将您的程序改为不用goto的请过目;
当然限于篇幅其中有些异常未进行处理
相互学习,请多指教.
using System;
class Class1
{
static void Main()
{
double a = 0,b = 0,result = 0;
string c = null;
bool control = true;
while(control == true)//控制计算过程
{
while(control == true)
{//检查除数是否为0
Input(out a,out b,out c);
if(b == 0 && (c == "/" || c == "%"))
{
Console.WriteLine("除数不能是0,请重新输入");
}
else
control = false;
}
result = Calculator(a,b,c);//计算
Console.WriteLine("计算结果是:"+result+
"\n你是否还要继续呢?Y/N"); //输出计算结果;
//输入"Y"或"y"将继续运算,否则将退出
c = Console.ReadLine();
if(c == "y" || c == "Y")
control = true;
else
control = false;
}
Console.WriteLine("再见了,同志!");
System.Threading.Thread.Sleep(2000);
}
static double Calculator(double a,double b,string c)
{//a,b为两个操作数,c为操作符;
double result = 0;
bool control = true;
while(control == true)
{
switch(c)
{
case "+":
result = a + b;
control = false;
break;
case "-":
result = a - b;
control = false;
break;
case "*":
result = a * b;
control = false;
break;
case "/":
result = a/b;
control = false;
break;
case "%":
result = a % b;
control =false;
break;
default:
Console.WriteLine("警告:输入操作符错误,请重新输入!");
break;
}
}
return result;
}
static bool Check(string str)
{//检查输入操作符是否合法
string s = "+-*/%";
if(s.IndexOf(str) == -1)//在串s中查找str,如果查不到,则返回-1;
{
Console.WriteLine("警告:输入操作符错误,请重新输入!");
return false;
}
else
return true;
}
static void Input(out double a,out double b,out string c)
{//out关键字表示引用,当调用方法时,
//在方法中对参数所做的任何更改都将反映在该变量中
a = 0;
b = 0;
c = null;//初始化参数
bool control = true;
while(control == true)//输入控制和检查
{
Console.WriteLine("请输入两个操作数:"+"\n第一个数:");
a = double.Parse(Console.ReadLine());
Console.WriteLine("第二个数:");
b = double.Parse(Console.ReadLine());
Console.WriteLine("请输入操作符:"+
"\n+:加法;"+
"\n-:减法;"+
"\n*:乘法;"+
"\n/:除法;"+
"\n%:取模;");
c = Console.ReadLine();
if(Check(c) == true)
{
control = false;
}
}
}
}