static void Main(string[] args)
{
int length = args.Length;
if (0 == length)
{
for (int i = 0; i < 20; i++)
{
ShowTest(false);
}
Console.WriteLine("你一共答对" + m_correctNum + "道题,共20道题");
}
else if (2 == length)
{
if ("-c" == args[0])
{
string str = args[1];
if (IsPositiveInt(str))
{
int count = int.Parse(str);
for (int i = 0; i < count; i++)
{
ShowTest(true);
}
}
else
{
Console.WriteLine("题目数量必须是 正整数!");
}
}
}
判断控制台传入主函数参数个数情况的处理
static private void ShowTest(bool showResult)
{
string expression = CreateExpression(); //生成试题
Queue<string> qexp = SplitExpress(expression); //把表达式存入队列
List<string> exp = InorderToPostorder(qexp); //表达式由中缀转为后缀
double result = 0;
IsResult(exp, out result);//根据后缀表达式计算结果
if (showResult)
{//打印试题及结果
Console.WriteLine(expression + "= " + result);
}
else
{//出题,并读入用户输入的值,判断是否正确
Console.WriteLine(expression);
Console.Write("?");
string input = Console.ReadLine();
if (IsNumeric(input))
{
double num = double.Parse(input);
if (num == result)
{
Console.WriteLine("答对啦,你真是个天才!");
m_correctNum++;
}
else
{
Console.WriteLine("再想想吧,答案似乎是" + result + "喔!");
}
}
}
}
进行出题或者人打印试题
static private string CreateExpression()
{
string expression = string.Empty;
int num;
int index;
char op;
List<int> position = new List<int>() {0, 2, 4 };
List<char> oplist = new List<char>() { '+','-', '*', '/'};
List<string> divlist = new List<string>() { "1","2","4","5","8"};
List<string> expList = new List<string>();
num = ran.Next(10);
expList.Add(num.ToString());
for (int i = 0; i < 3; i++)
{
index = ran.Next(oplist.Count());
op = oplist[index];
if ('/' == op)
{
oplist.RemoveAt(3);
index = ran.Next(divlist.Count());
num = int.Parse(divlist[index]);
}
else
{
num = ran.Next(10);
}
expList.Add(op.ToString());
expList.Add(num.ToString());
}
int pos;
index = expList.IndexOf("/");
if (-1 == index)
{
pos = position[ran.Next(3)];
}
else
{
if (1 == index)
{
position.RemoveAt(1);
}
else if (3 == index)
{
position.RemoveAt(2);
}
pos = position[ran.Next(position.Count())];
}
expList.Insert(pos, "(");
expList.Insert(pos + 4, ")");
foreach (string str in expList)
{
expression += str;
}
return expression;
}
利用栈的应用,将中序转换为后序,再将后序输出。随机数是生成4个,符号也是4个,分别用0丶1丶2丶3表示,括号先设置为每两个数之间。
运行后的图片:

