版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/grooowing/article/details/40976701
一个月以来犯错较多且难以发现错误的:
1,循环体内i,j,k.混用:
for example:
for(i=0;i<n;i++){
for(i=0;i<m;i++){
//statement;
}
}
或:
for(i=0;i<n;i++){
for(j=0;j<m;i++){
//statement;
}
}
或者在循环体中不小心改变了循环变量的值等等。
2,更新多个变量犯错。
int func(int x,int y);
//ues func() to update p,q;
int p,q;
p=func(p,q);
q=func(p,q);//note the p has been changed
3,处理字符串时,忽略在结尾处添加'\0'
3.2处理字符串中“数字”时,没有减去'0',或只考虑一位数的情况。
int len=strlen(str);
int temp=0;
for(j=5;j<len;j++){ <pre name="code" class="cpp">temp=temp*10+str[j]
//should be :temp=temp*10+str[j]-'0';}S[top]=temp;//S[top]=str[5]-'0'只考虑了一位情况
4,类型定义错误。
//int instead of char
int m[50];
scanf("%s",m);
printf(m);
//or char instead of int;
char n[50];
if(statement){
n++;
}
5,数组越界,运行时未报错。
//这个最后居然把x.size置为0了。。
struct bigint{
int digit[200];
int size;
};
void func(bigint x){
int i;
for(i=0;i<201;i++){
x.digit[i]=0;
}
}
6,边界错误。
如,求a以内连续奇数素数对的个数。(如3,5)
for(i=2;i<a;i++)
if(isPrime(i) && isPrime(i+2))
count++;
以上虽然i<a,但是却在循环中出现了i+2.
7,没有注意递归出口
void preorder(int root){
if(root!=0)
printf("%d ",tree[root].x);
preorder(tree[root].left);
preorder(tree[root].right);
}
注意上述代码在root=0时会无限执行preorder(tree[root].left);
应该为:
void preorder(int root){
if(root==0)
return;
printf("%d ",tree[root].x);
preorder(tree[root].left);
preorder(tree[root].right);
}
另外,树里递归出口很多都是if(root==0)。
比如,求树的高度
int height(int root){
if(root==0)return 0;
int lefth=0,righth=0;
lefth=height(tree[root].left);
righth=height(tree[root].right);
tree[root].h=max(lefth,righth)+1;
tree[root].delth=lefth-righth;//高度差
return tree[root].h;
}
8,在条件中的"++"运算符
while(str++<p){
if(str[0]!='A'){
puts("1");
printf("a,b,c,%d,%d,%d\n",a,b,c);
return false;
}
a++;
}
注意在循环中用到了str[0],但是此时的str已经不再是循环判定中的str了,是自增之后的str;
我这里本来是想判定从str开始到p结束(不包括p)的字符,显然起始位没判断,又多判断了p位.
应该是下面这样:
while(str<p){
if(str[0]!='A'){
puts("1");
printf("a,b,c,%d,%d,%d\n",a,b,c);
return false;
}
str++;
a++;
}
9,递归出口错误。如DFS想在res为true时推出循环,
应该为下面:
//DFS,注意递归出口是从某鳄鱼可以跳到陆地
bool DFS(int x){
//DFS递归出口易错
bool res=false;
int i;
visited[x]=true;
if(issaved(point[x])){
return true;
}
for(i=0;i<number;i++){
if(!visited[i]&&dist(point[x],point[i])<=step){
//绝对不可以写
//return DFS(i);
//相当于for(i=0;i<n;i++)return i;
//除了i为0时会return出来,其他的不会return
//事实上出口是return true。当res为false时,还要继续
res=DFS(i);
if(res)return true;
}
}
return false;
}
以及BFS易错点:。。。
//注意两个visited[]位置。
//一开始我只写一个visited,在print后,也就是打印相当于访问
//如下
/*
void BFS(int x){
while(!Q.empty())Q.pop();
Q.push(x);
int i;
while(!Q.empty()){
int t=Q.front();
Q.pop();
printf(" %d",t);
visited[i]=true;//这样在打印前可能入队列很多次。。。。
//建议可以在打印前判断是否是访问过。只不过会浪费一些队列位置
for(i=0;i<n;i++){
if(!visited[i] && map[i][t]==1){
//printf("\nt,i:%d,%d",t,i);
Q.push(i);
}
}
}
}
*/
void BFS(int x){
while(!Q.empty())Q.pop();
Q.push(x);
int i;
visited[x]=true;///
while(!Q.empty()){
int t=Q.front();
Q.pop();
printf(" %d",t);
for(i=0;i<n;i++){
if(!visited[i] && map[i][t]==1){
//printf("\nt,i:%d,%d",t,i);
Q.push(i);
visited[i]=true;
}
}
}
}