一个轻量级、跨平台的四则运算计算器
功能特性 • 快速开始 • 使用指南 • 项目结构 • 开发 •
| 平台 | 编译器 | 依赖库 |
|---|---|---|
| Linux | GCC 4.8+ | readline, ncurses |
| Windows | MinGW-w64 | 无额外依赖 |
| MSYS2 | GCC | 无额外依赖 |
Ubuntu/Debian:
sudo apt-get update
sudo apt-get install build-essential libreadline-dev libncurses-dev
CentOS/RHEL/Fedora:
sudo yum install gcc make readline-devel ncurses-devel
macOS (使用 Homebrew):
brew install readline
# 克隆仓库
git clone https://github.com/hanphone/calculator.git
cd calculator
# Linux
make -f Makefile.linux
# Windows (MinGW)
make -f Makefile.windows
# MSYS2
make -f Makefile.msys2
# 交互模式
./calculator
# 文件批处理模式
./calculator input.txt output.txt
启动程序后,输入数学表达式即可得到计算结果:
$ ./calculator
Welcome to C Calculator
You can enter 'help' to ask for help.
You can quit through entering 'quit'.
Enter: 1+2*3
Result:7.000000
Enter: (1+2)*3
Result:9.000000
Enter: -5+10
Result:5.000000
Enter: quit
Successful Exit.
支持的运算符:
| 运算符 | 说明 | 优先级 |
|---|---|---|
+ |
加法 | 1 (低) |
- |
减法 | 1 (低) |
* |
乘法 | 2 (高) |
/ |
除法 | 2 (高) |
() |
括号 | 最高 |
内置命令:
help - 显示帮助信息quit - 退出程序创建包含表达式的输入文件:
$ cat input.txt
1+2
3*4
(5+6)*2
10/0
运行批处理:
$ ./calculator input.txt output.txt
查看结果:
$ cat output.txt
Result1:3.000000
Result2:12.000000
Result3:22.000000
Result4:Error - Division by zero
calculator/
├── src/ # 源代码目录
│ ├── main.c # 程序入口和主循环
│ ├── calculator.c/.h # 表达式解析和计算核心
│ ├── stack.c/.h # 动态栈数据结构
│ ├── platform.c/.h # 平台抽象层(输入/输出)
│ └── error.h # 错误码定义
├── tests/ # 测试代码
│ └── test_basic.c # 基础功能单元测试
├── Makefile.linux # Linux 构建配置
├── Makefile.windows # Windows 构建配置
├── Makefile.msys2 # MSYS2 构建配置
└── README.md # 项目文档
Stack (栈) - src/stack.c
double 和 char 两种数据类型Calculator (计算器) - src/calculator.c
Platform (平台层) - src/platform.c
cd tests
gcc -o test_basic test_basic.c ../src/stack.c ../src/calculator.c ../src/platform.c -I../src -lm
./test_basic
# Linux - 启用调试符号
make -f Makefile.linux clean
make -f Makefile.linux CFLAGS="-g -DDEBUG"
# 使用 GDB 调试
gdb ./calculator
</a>