C语言图形面积计算程序strcmp字符串比较异常问题排查
问题排查与修复方案
直接触发else分支的核心原因
fgets函数会读取输入末尾的换行符:你输入图形名称按下回车后,fgets()会把换行符\n一起存入shape数组,比如输入TRIANGLE,实际shape中存储的内容是"TRIANGLE\n",用strcmp和无换行的"TRIANGLE"比较自然返回非0值,直接进入else分支。
其他隐藏问题
- 缺少必要头文件:代码使用
printf、scanf、fgets需要引入<stdio.h>,使用strcmp需要引入<string.h>,部分编译器可强制通过但属于不规范写法。 scanf读取数值后会在输入缓冲区残留换行符,下一次循环的fgets会直接读取到这个空行,导致第二次运行时直接触发else分支。- 用int类型存储面积会丢失精度,尤其是圆形面积涉及π的浮点计算,转int会直接截断小数部分。
- 面积计算函数返回
printf的返回值(打印的字符数)无实际意义,且输出未加换行符,多轮运行时输出内容会粘连。
修复后完整代码
#include <stdio.h> #include <string.h> #define pi 3.14 // 面积函数调整为void类型,不需要返回值 void areaTriangle (int valueBase, int valueHeight); void areaSquare (int valueSide); void areaCircle (int valueRadius); // 去除fgets读取到的末尾换行符 void trim_newline(char *str) { while(*str) { if(*str == '\n') { *str = '\0'; break; } str++; } } // 清空scanf残留的缓冲区换行 void clear_buffer() { while(getchar() != '\n'); } int main() { while (1) { char shape[20]; printf("what geometry shape do you want to find? (TRIANGLE/SQUARE/CIRCLE/EXIT) ="); fgets(shape, 20, stdin); trim_newline(shape); // 先去除换行再做匹配 if (strcmp(shape, "TRIANGLE") == 0) { int height; int base; printf("height = "); scanf("%d", &height); printf("base = "); scanf("%d", &base); clear_buffer(); areaTriangle(height, base); } else if (strcmp(shape, "SQUARE") == 0) { int side; printf("side = "); scanf("%d", &side); clear_buffer(); areaSquare(side); } else if (strcmp(shape, "CIRCLE") == 0) { int radius; printf("radius = "); scanf("%d", &radius); clear_buffer(); areaCircle(radius); } else if (strcmp(shape, "EXIT") == 0) { // 新增退出逻辑,避免死循环只能强制终止 printf("program exit\n"); break; } else printf("OTHER SHAPE NOT AVAILABLE\n"); } return 0; } void areaTriangle (int valueBase, int valueHeight) { double area = (valueBase * valueHeight) / 2.0; printf("The area of this triangle is = %.2f\n", area); } void areaSquare (int valueSide) { int area = valueSide * valueSide; printf("The area of this square is = %d\n", area); } void areaCircle (int valueRadius){ double area = pi * valueRadius * valueRadius; printf("The area of this circle is = %.2f\n", area); }
内容的提问来源于stack exchange,提问作者imnotarobot
相关产品推荐
相关产品推荐

