Week 1 综合项目:命令行计算器
项目目标
创建一个功能完整的命令行计算器,巩固本周所学知识。
功能要求
- 支持加减乘除四则运算
- 支持历史记录查看
- 支持清除历史
- 输入验证
- 循环菜单
实现步骤
1. 创建项目
cd /Users/yao/Projects
dotnet new console -n Calculator
cd Calculator
code .2. 完整代码
using System;
using System.Collections.Generic;
class Calculator
{
static List<string> history = new List<string>();
static void Main()
{
while (true)
{
Console.WriteLine("\n=== 计算器 ===");
Console.WriteLine("1. 加法");
Console.WriteLine("2. 减法");
Console.WriteLine("3. 乘法");
Console.WriteLine("4. 除法");
Console.WriteLine("5. 查看历史");
Console.WriteLine("6. 清除历史");
Console.WriteLine("7. 退出");
Console.Write("请选择: ");
string? choice = Console.ReadLine();
if (choice == "7") break;
switch (choice)
{
case "1":
Calculate("+");
break;
case "2":
Calculate("-");
break;
case "3":
Calculate("*");
break;
case "4":
Calculate("/");
break;
case "5":
ShowHistory();
break;
case "6":
ClearHistory();
break;
default:
Console.WriteLine("无效选择");
break;
}
}
}
static void Calculate(string op)
{
Console.Write("输入第一个数: ");
if (!double.TryParse(Console.ReadLine(), out double a))
{
Console.WriteLine("输入无效");
return;
}
Console.Write("输入第二个数: ");
if (!double.TryParse(Console.ReadLine(), out double b))
{
Console.WriteLine("输入无效");
return;
}
double result = op switch
{
"+" => a + b,
"-" => a - b,
"*" => a * b,
"/" => b != 0 ? a / b : double.NaN,
_ => 0
};
if (double.IsNaN(result))
{
Console.WriteLine("错误:除数不能为0");
return;
}
string record = $"{a} {op} {b} = {result}";
history.Add(record);
Console.WriteLine($"结果: {result}");
}
static void ShowHistory()
{
if (history.Count == 0)
{
Console.WriteLine("暂无历史记录");
return;
}
Console.WriteLine("\n=== 历史记录 ===");
for (int i = 0; i < history.Count; i++)
{
Console.WriteLine($"{i + 1}. {history[i]}");
}
}
static void ClearHistory()
{
history.Clear();
Console.WriteLine("历史记录已清除");
}
}运行测试
dotnet run扩展挑战
- 添加开方、幂运算
- 支持连续计算
- 保存历史到文件
- 支持括号运算
对比Odoo
这个项目类似Odoo中的wizard(向导),都是:
- 交互式操作
- 临时数据存储
- 菜单驱动