C语言while循环使用continue后异常停止该如何修复
问题根因与修复方案
根因说明
代码的卡死问题由continue跳过start自增逻辑导致:
当start取值为4的倍数时,if(start % 4 == 0)判断成立,执行continue直接跳转至下一次循环条件判断,完全跳过了代码末尾的start++语句,start的值永远停留在该4的倍数上,循环条件start <= end永远成立,程序死锁,看起来就像停在3的输出后不再运行。
修复方案
方案1:在continue分支补充自增逻辑
在判断为4的倍数的分支中,先执行start++再调用continue,保证循环变量每次都会更新:
#include<stdio.h> int main(){ int start, end; printf("Enter the starting point: "); scanf("%d", &start); printf("Enter the ending point: "); scanf("%d", &end); while(start <= end){ if(start % 4 == 0){ start++; continue; } // 要输出%符号需要写两个%,否则会触发格式字符串警告 printf("Loading...%d%%\n", start); start++; } return 0; }
方案2:将自增逻辑前置(更推荐,避免分支漏写自增)
把start自增放到循环最开头,无需在多个分支重复写自增语句,逻辑更简洁:
#include<stdio.h> int main(){ int start, end; printf("Enter the starting point: "); scanf("%d", &start); printf("Enter the ending point: "); scanf("%d", &end); // 提前减1抵消首次循环的前置自增 start--; while(start < end){ start++; if(start % 4 == 0){ continue; } printf("Loading...%d%%\n", start); } return 0; }
内容的提问来源于stack exchange,提问作者OverHeaven
相关产品推荐
相关产品推荐

