C语言绘制双矩形脚本出现无限循环问题求排查指导
问题排查与修正方案
1. 无限循环直接原因
外层遍历y的for循环迭代变量写反:
原代码:for (int y = 0; y < h; h++)
你每次循环自增的是h而不是y,导致y永远停留在0,永远满足y < h的判断条件,程序就会无限执行外层循环。
修正为:for (int y = 0; y < h; y++)
2. 其他逻辑错误
2.1 画布宽高计算错误
注释要求是取size1和x_offset + size2的最大值作为画布宽度w,但你写的是加法逻辑,同理高度h也使用了错误的加法逻辑:
原代码:
int w = (size1 + (x_offset + size2)); int h = (size1 + (y_offset + size2));
修正为(用三目运算符实现取最大值):
int w = size1 > (x_offset + size2) ? size1 : (x_offset + size2); int h = size1 > (y_offset + size2) ? size1 : (y_offset + size2);
2.2 isAtBorder函数判断逻辑错误
原代码的判断条件写漏了左边的coord ==,导致只要offset + size不为0,第二个判断永远为真:
原代码:if (coord == offset || (offset + size))
修正为:if (coord == offset || coord == (offset + size))
2.3 换行输出错误
原代码输出换行的语句写法错误,应该使用转义字符\n实现换行:
原代码:printf ("");
修正为:printf("\n");
修正后的完整代码
#include <stdio.h> #include <stdlib.h> /* * Determines if coord is in range between * offset (INCLUSIVE) and offset + size (EXCLUSIVE) */ int isInRange(int coord, int offset, int size) { // if coord is in range, return 1 if ((coord >= offset) && (coord < (offset + size))) { return 1; } // else, return 0 else { return 0; } return 0; } /* * Determines if coord is at border of offset or * offset + size */ int isAtBorder(int coord, int offset, int size) { // if coord is equal to offset or offset + size if (coord == offset || coord == (offset + size)) { return 1; } // return 1, else return 0 else { return 0; } return 0; } void squares(int size1, int x_offset, int y_offset, int size2) { //compute the max of size1 and (x_offset + size2). Call this w int w = size1 > (x_offset + size2) ? size1 : (x_offset + size2); //compute the max of size1 and (y_offset + size2). Call this h int h = size1 > (y_offset + size2) ? size1 : (y_offset + size2); //count from 0 to h. Call the number you count with y for (int y = 0; y < h; y++) { //count from 0 to w. Call the number you count with x for (int x = 0; x < w; x++) { //check if EITHER // ((x is between x_offset and x_offset +size2) AND if (((isInRange(x, x_offset, size2) == 1) && // y is equal to either y_offset OR y_offset + size2 - 1) (isAtBorder(y, y_offset, size2 - 1) == 1)) // OR || // ((y is between y_offset and y_offset + size2) AND ((isInRange(y, y_offset, size2) == 1) && // x is equal to either x_offset OR x_offset + size2 -1) (isAtBorder(x, x_offset, size2-1)))) { // if so, print a * printf("*"); } //if not, // check if EITHER // x is less than size1 AND (y is either 0 or size1-1) else { if (((x < size1) && (isAtBorder(y, 0, size1 - 1) == 1)) // OR || // y is less than size1 AND (x is either 0 or size1-1) ((y < size1) && (isAtBorder(x, 0, size1 - 1) == 1))) { //if so, print a # printf("#"); } //else print a space else { printf(" "); } } } //when you finish counting x from 0 to w, //print a newline printf("\n"); } }
内容的提问来源于stack exchange,提问作者Quinn
相关产品推荐
相关产品推荐

