C语言程序最后一条printf语句未执行的问题求助
问题分析与修复方案
核心错误(导致最后一条printf被跳过的原因)
第一个scanf调用存在指针使用错误:
scanf("%255s", &carModel); // 错误写法
carModel本身是char*类型的指针,指向malloc分配的内存空间,scanf的%s格式符要求接收char*类型参数。传递&carModel相当于传入char**类型指针,类型不匹配会触发未定义行为,破坏程序内存布局,导致后续代码无法正常执行。
修正为:
scanf("%255s", carModel); // 正确写法,直接传递指针
额外逻辑错误
每英里行驶成本的计算公式完全颠倒:
costMile = mpg / gasCost; // 错误逻辑
正确逻辑应为每加仑油价 ÷ 每加仑行驶英里数,即:
costMile = gasCost / mpg;
举个例子:油价3美元/加仑,油耗30英里/加仑,每英里成本是3/30=0.1美元,原公式会得出错误的10,完全不符合实际。
其他优化建议
- 每次
malloc后检查内存是否分配成功,避免空指针访问:
carModel = malloc(256); if (carModel == NULL) { fprintf(stderr, "内存分配失败\n"); return 1; }
- 程序结束时释放
malloc分配的内存,避免内存泄漏:
free(carModel);
修复后的完整代码
#include <stdio.h> #include <stdlib.h> int main(void) { char *carModel; float tankRange; float gasCost; float costTank; float gallonsTank; // 满油箱油量 float mpg; // 每加仑行驶英里数 float costMile; carModel = malloc(256); if (carModel == NULL) { fprintf(stderr, "内存分配失败\n"); return 1; } printf("What is the model of car? " ); scanf("%255s", carModel); printf("How many miles can be driven on a full tank? " ); scanf("%f", &tankRange); printf("What is the gas cost per gallon? " ); scanf("%f", &gasCost); printf("How much does it cost to fill the tank? " ); scanf("%f", &costTank); gallonsTank = costTank / gasCost; mpg = tankRange / gallonsTank; costMile = gasCost / mpg; printf("Amazing! %s has an mpg of %.3f per gallon! You spent $%.2f to drive one mile!\n", carModel, mpg, costMile); free(carModel); return 0; }
内容的提问来源于stack exchange,提问作者Santiago
相关产品推荐
相关产品推荐

