C语言switch语句case匹配counter输出年龄阶段问题求助
C语言代码问题修复指南
核心错误点梳理
- 成年/未成年判断逻辑错误:你将
Age < 18的判断嵌套在了Age > 18的分支内部,该分支永远不可能触发,未成年提示永远不会输出。 - 分段计数器
counter计算逻辑完全失效:现有代码中while (++counter <= 10);末尾跟了空语句分号,只要年龄小于等于100,计数器就会从0一直自增到11才停止,和年龄完全没有关联,自然无法匹配switch的对应case。 - 缺少年龄合法性校验:如果用户输入的出生年份大于当前年份,会得到负数年龄,没有对应的处理逻辑。
修复思路
你的switch分支编号刚好对应年龄十位上的数值,完全不需要循环计算,直接用C语言整数除法的特性(截断小数)就能得到正确的counter值:
- 0-9岁除以10得到0,对应case 0
- 10-19岁除以10得到1,对应case 1,刚好输出你需要的
you are in your tens / teens - 20-29岁除以10得到2,对应case 2,以此类推
- 超过100岁直接赋值counter为10即可
修复后的完整代码
#include <stdio.h> int main() { int YoB, CY, Age; unsigned int counter = 0; printf("Please enter your year of birth: "); // 若使用非VS编译器,请将scanf_s改为scanf scanf_s("%d", &YoB); printf("Please enter the current year: "); scanf_s("%d", &CY); Age = CY - YoB; printf("Entered year of birth %d\n", YoB); printf("Entered current year %d\n", CY); printf("You are %d years old\n \n", Age); // 修复成年/未成年判断逻辑 if (Age >= 18) { puts("You are an adult\n"); } else { puts("You are a minor\n"); } // 年龄合法性校验 if (Age < 0) { puts("invalid age!"); return 0; } // 修复counter计算逻辑 if (Age > 100) { counter = 10; } else { counter = Age / 10; } switch (counter) { case 0: puts("You are less than 10\n"); break; case 1: puts("you are in your tens / teens\n"); break; case 2: puts("You are in your twenties\n"); break; case 3: puts("You are in your thirties\n"); break; case 4: puts("You are in your fourties\n"); break; case 5: puts("You are in your fifties\n"); break; case 6: puts("You are in your sixties\n"); break; case 7: puts("You are in your seventies\n"); break; case 8: puts("You are in your eighties\n"); break; case 9: puts("You are in your nineties\n"); break; case 10: puts("You are a 100+!!\n"); break; default: puts("invalid age!"); break; } return 0; }
内容的提问来源于stack exchange,提问作者fvaisal
相关产品推荐
相关产品推荐

