一个控制台应用程序,用于自动出题,并对用户的计算结果进行作出判断。
原代碼如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace Math
{
class Program
{
enum Operate { Addition, Subtration }
static void Main(string[] args)
{
welcome(); // 調用自定義方法,顯示歡迎介面
int total, t, f; // 分別用于存儲試題總數,答對的題數,答錯的題數
bool reStart; // 存儲用戶是否愿意再試一次
int intRadix = CreateRadix();
Random random = new Random(intRadix);
do
{
reStart = false;
Console.WriteLine("\n測試現在開始,請留意題目!\n");
total = 10;
t = 0;
f = 0;
Operate oper = (Operate)(random.Next(0, 2));
int leftOperand = 0;
int rightOperand = 0;
int result = 0; // 存儲用戶輸入的結果
for (int i = 0; i < total; i++)
{
#region 出題
oper = (Operate)(random.Next(0, 2));
leftOperand = random.Next(1, 100);
if (oper == Operate.Subtration)
{
rightOperand = random.Next(0, leftOperand);
}
else
{
rightOperand = random.Next(0, 100 - leftOperand);
}
do
{
Console.Write("<{0}> {1} {2} {3} = ", (i + 1).ToString().PadLeft(total.ToString().Length, '0'), leftOperand.ToString().PadLeft(2, ' '), oper == Operate.Addition ? "+" : "-", rightOperand.ToString().PadLeft(2, ' '));
} while (!int.TryParse(Console.ReadLine(), out result));
#endregion
#region 判斷結果是否正确
if (oper == Operate.Addition)
{
if (result == leftOperand + rightOperand)
{
Console.Write(" ------------恭喜你,答對啦!!!\n");
t++;
}
else
{
Console.Write(" ------------很遺憾,正确答案應是:{0}!\n", (leftOperand + rightOperand).ToString().PadLeft(2, ' '));
f++;
}
}
if (oper == Operate.Subtration)
{
if (result == leftOperand - rightOperand)
{
Console.Write(" ------------恭喜你,答對啦!!!\n");
t++;
}
else
{
Console.Write(" ------------很遺憾,正确答案應是:{0}!\n", (leftOperand - rightOperand).ToString().PadLeft(2, ' '));
f++;
}
}
#endregion
}
#region 顯示考生的成績
Console.WriteLine("_______________________________________________________________");
Console.WriteLine("\n--- 本次你完成了{0} 道試題, 答對{1} 道, 答錯{2} 道!", total, t, f);
Console.Write("\n\n感謝你的參与,再測試一次嗎?(Y/N) ");
#region 判斷用戶是否原意再測試一次
try
{
if (Console.ReadLine().Substring(0, 1).ToUpper() == "Y")
{
reStart = true;
Console.WriteLine("\n\n\n\n另一組新試題:");
}
}
catch
{
}
#endregion
} while (reStart);
#endregion
}
#region 程序運行前的介紹
private static void welcome()
{
Console.WriteLine("**********************************");
Console.WriteLine("** 項目: '兩位數加減法'測試題 ***");
Console.WriteLine("** 制作: C_B_Lu ***");
Console.WriteLine("** 日期: 2007年月日 ***");
Console.WriteLine("**********************************\n");
}
#endregion
#region 創建一個基數,用于初始發隨來數
/// <summary>
/// 創建一個基數,用于初始發隨來數
/// </summary>
/// <returns></returns>
static int CreateRadix()
{
Console.Write("請隨意輸入一個數字:");
int intRadix;
if (int.TryParse(Console.ReadLine(), out intRadix))
{
return intRadix;
}
else
{
return CreateRadix();
}
}
#endregion
}
}