C语言程序输入后直接退出,if-else语句未执行,求错误原因
C语言矩形面积周长比较程序的错误分析与修复
你的程序输入后直接关闭、if-else逻辑未执行,核心问题及修复方案如下:
1. 致命错误:scanf参数传递错误
C语言中scanf需要接收变量的内存地址来存储输入值,你当前的写法直接传递变量值而非地址:
scanf("%d%d", length, breadth);
这会导致程序写入非法内存,触发崩溃,输入后程序直接终止,根本无法走到if-else判断环节。
正确写法需在变量前添加&取地址符:
scanf("%d%d", &length, &breadth);
2. else分支逻辑描述错误
你的else分支输出文本为"The area is equal to or greater than the perimeter",但else的触发条件是area <= perimeter,逻辑完全矛盾,正确输出应为:
printf("The area is equal to or less than the perimeter\n");
3. 可选优化:避免程序执行后直接退出
如果在Windows控制台运行程序,执行完毕后窗口会直接关闭,无法查看输出结果。可在return 0;前添加暂停代码:
getchar(); // 跨平台的暂停方式,也可使用system("pause")(仅Windows有效)
修复后的完整代码
#include<stdio.h> // 未用到math库函数,可删除#include<math.h> int main(){ int length,breadth,perimeter,area; printf("Enter the length and breadth of the rectangle respectively\n"); scanf("%d%d", &length, &breadth); area = length * breadth; perimeter = 2 * (length + breadth); // 简化周长计算,与原逻辑等价 if (area > perimeter) { printf("The area is greater than the perimeter\n"); } else{ printf("The area is equal to or less than the perimeter\n"); } getchar(); // 暂停程序以便查看输出 return 0; }
内容的提问来源于stack exchange,提问作者Krutarth Nandani
相关产品推荐
相关产品推荐

