C / C ++ programming BUG

1, the operation result out of range error

// mul = n[i] * b + carry;
// n数组和b都为int类型,mul为long long
// 假设b为十位数,运算结果极可能超出int范围,得出错误结果,正确应如下
mul = (long long)n[i] * b + carry;

2, if the statement "and" consolidation issues

if(depth == N - 1){
	if(last >= rem)
		_count++;
}
//以下合并错误,depth == N - 1 为1 且 last >= rem 为0 时执行else,原问题此情况下不执行
//if(depth == N - 1 && last >= rem){
//	_count++;
//}
else
{
	for(int k = min(last, rem); k >= 0; k--){
		solve(depth + 1, k, rem - k);
	}
}

3, the array index error from zero, noting array index related issues! !

/*
    在写《挑战程序设计竞赛》P129页题目中,个人写了个bug,很难发现
    发现后,以下是此bug程序的部分代码
*/
const int MAX_P = 100;
const int MAX_Q = 100;
int P = 20;
int Q = 3;
int A[MAX_Q] = {3, 6, 14};

int dp[MAX_P][MAX_P];

int solve(){
	for(int w = 1; w < P; w++){ // 宽度增大
		// for(int i = 0, j = i + w; j < P; i++, j++){
		for(int i = 1, j = i + w; j <= P; i++, j++){
			dp[i][j] = 0; // 假设i,j区间没有要释放的犯人
			for(int k = 0; k < Q; k++){
				if(i <= A[k] && j >= A[k]){ // 存在在区间要释放的犯人,此处,若用以上错误代
     				                            // 码,i从0开始,却表达现实生活第1个,进行
   			                                    // 和A[k]比较会有问题
					// 省略......
				}
			}
		}
	}
	return dp[0][P - 1];
}

4, operator precedence problems, a good habit is to play brackets, or may be wrong. << 1 Note 3 - 1 equivalent to 1 << (3 - 1) instead of (1 << 3) --1

5、

if(c[x + 1][y] == 0){ // if(c[x + 1][y] != 0){ // 错误原因:逻辑错误,应该为当前坐标没有计算出值时计算值
	int sum = cal(a, n, x + 1, y);
	c[x + 1][y] = sum;
	calsum(a, n, x + 1, y, c);
}

Guess you like

Origin blog.csdn.net/ertcmmy/article/details/84708292