测试和调试阶乘计算器
在这最后一步中,你将学习如何使用各种测试技术和调试策略来全面测试和调试阶乘计算器。
让我们创建一个包含多个测试用例和调试功能的综合测试程序。在 ~/project
目录下创建一个名为 factorial_test.c
的文件:
cd ~/project
touch factorial_test.c
#include <stdio.h>
#include <assert.h>
#include <limits.h>
// 带有详细错误检查的阶乘计算函数
int calculateFactorial(int n) {
// 调试打印以跟踪函数调用
printf("DEBUG: Calculating factorial for %d\n", n);
// 验证输入范围
if (n < 0) {
fprintf(stderr, "ERROR: Factorial undefined for negative numbers\n");
return -1;
}
// 处理特殊情况
if (n == 0 || n == 1) return 1;
// 带有溢出保护的阶乘计算
long long factorial = 1;
for (int i = 2; i <= n; i++) {
factorial *= i;
// 溢出检查
if (factorial > INT_MAX) {
fprintf(stderr, "ERROR: Factorial exceeds integer limit\n");
return -1;
}
}
return (int)factorial;
}
// 验证阶乘计算的测试函数
void runTests() {
// 包含预期结果的测试用例
struct TestCase {
int input;
int expected;
} tests[] = {
{0, 1}, // 边缘情况:0!
{1, 1}, // 边缘情况:1!
{5, 120}, // 正常情况:5!
{10, 3628800} // 较大数字
};
int numTests = sizeof(tests) / sizeof(tests[0]);
printf("Running %d test cases...\n", numTests);
// 遍历测试用例
for (int i = 0; i < numTests; i++) {
int result = calculateFactorial(tests[i].input);
// 断言式测试
if (result == tests[i].expected) {
printf("Test case %d PASSED: factorial(%d) = %d\n",
i+1, tests[i].input, result);
} else {
printf("Test case %d FAILED: Expected %d, Got %d\n",
i+1, tests[i].expected, result);
}
}
}
int main() {
// 运行综合测试套件
runTests();
// 交互式测试模式
int number;
printf("\nEnter a number to calculate its factorial (or negative to exit): ");
while (scanf("%d", &number) == 1 && number >= 0) {
int result = calculateFactorial(number);
if (result != -1) {
printf("Factorial of %d is: %d\n", number, result);
}
printf("\nEnter another number (or negative to exit): ");
}
return 0;
}
编译并运行程序:
gcc factorial_test.c -o factorial_test
./factorial_test
示例输出如下:
Running 4 test cases...
DEBUG: Calculating factorial for 0
Test case 1 PASSED: factorial(0) = 1
DEBUG: Calculating factorial for 1
Test case 2 PASSED: factorial(1) = 1
DEBUG: Calculating factorial for 5
Test case 3 PASSED: factorial(5) = 120
DEBUG: Calculating factorial for 10
Test case 4 PASSED: factorial(10) = 3628800
Enter a number to calculate its factorial (or negative to exit):
展示的关键调试和测试技术:
- 使用调试打印语句跟踪函数执行
- 涵盖边缘情况的综合测试用例
- 对无效输入的错误处理
- 溢出保护
- 断言式测试
- 交互式测试模式
调试技巧:
- 使用
printf()
进行日志记录和跟踪函数调用
- 显式处理边缘情况
- 实现输入验证
- 使用
long long
进行较大数字的计算
- 创建测试套件以验证不同场景