作者:葛伟杰
链接:https://www.zhihu.com/question/60719584/answer/209568442
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
# OI 调试技巧
> 2o17.8.6 By gwj
> QAQ全部临时写的,代码没有测试过正确性什么的
+ 1 小黄鸭调试法
```txt
来自维基:小黄鸭调试法是软件工程中使用的调试代码方法之一。
就是在程序的调试、纠错或测试过程中,耐心地向小黄鸭解释每一行程序的作用,以此来激发灵感。
```
+ 2 输出中间值
```txt
在关键位置输出值
适用于以下一些:
1.数据输入,输出
2.死循环,盏溢出
3.过程值,语义分析(较痛苦
much more :
适用于细节手误没看到。
操作函数化,分块测试,能独立测试的算法部分先验证其正确性。
对照神犇代码,用一样的部分替换掉自己代码,并测试答案。
```
+ 3 断点、单步
```txt
GDB调试技巧
我也不会啊,我也很无奈啊。
```
+ 4 对拍
```
大量随机数据测试,正确性判断
步骤
1. 写好程序和暴力
2. 写好数据生成器
3. 写好对拍文件
———————————————————————
关于数据生成器
如何生成给定值域内的数字?
如何生成一棵树?
如何生成一张图?
———————————————————————
”Windows 环境下对拍文件.bat
“用重定向的方式代替代码内的文件输入输出
@echo off "关掉屏幕显示
:loop "循环
rand.exe %random% > input.txt “随机生成数据
test.exe < input.txt > test.out ”运行错解
std.exe < input.txt > std.out “运行标程
fc test.out std.out “比较输出
if errorlevel 1 pause ”如果不同就停下来
goto loop “重复循环
———————————————————————
#Linux 环境下对拍文件.sh
#!/bin/bash
while true; do
./rand > input.txt
./test < input.txt > test.out
./std < input.txt > std.out
if diff std.out test.out; then
printf "AC\n"
else
printf "Wa\n"
exit 0
fi
done
————————————————————————
//Windows 数据生成器 .cpp
#include<iostream>
#include<string>
#include<cstdlib>
#include<ctime>
#include<sstream>
using namespace std;
#define random(a, b) ((a)+rand()%((b)-(a)+1)) //Integer[a,b]
int main(int argc, char *argv[]){
//1. 随机数初始化
stringstream ss;
int seed = time(NULL);
if(argc){
ss<<argv[1];
ss>>seed;
}
srand(seed);
//2. 数据生成
int T = random(1, 41);
while(T--){
int rt=random(2,8), bx=random(1,9), by=random(1,10);
cout<<rt<<" "<<bx<<" "<<by<<"\n";
char cc[5] = "GRHC";
while(rt--){
int z=random(0,3), x=random(1,9), y=random(1,10);
cout<<cc[z]<<" "<<x<<" "<<y<<"\n";
}
cout<<"\n";
}
cout<<"0 0 0\n";
return 0;
}
```
+ 5 其他一些
```txt
1. 重写代码(雾
2. 拒绝调试(逃
```