C语言if语句故障:无法计算盈亏,程序无输出请求技术协助
问题分析与修复方案
你的代码未执行判断逻辑的核心原因是:只处理了成本价≠售价的两种情况,完全遗漏了成本价等于售价的场景。如果输入的成本价和售价数值相等,两个if的条件都不满足,程序会直接执行return 0结束,看起来就像所有判断逻辑都没运行。
除此之外,代码还有几个明显的问题需要修正:
- 亏损计算时,
n = y - x会得到负数,输出的亏损金额为负数,不符合常理 - 用整数计算利润率会导致精度丢失,甚至出现除以0的错误(比如成本价大于100时,
100/x的整数结果为0) - 缺少分支覆盖所有输入情况,逻辑不完整
修复后的代码
#include <stdio.h> int main() { int cost, sell; int amount; char percent = '%'; char dollar = '$'; printf("Enter cost of item:- "); scanf("%d", &cost); printf("Enter selling price of item:- "); scanf("%d", &sell); if (cost < sell) { amount = sell - cost; // 用浮点型计算利润率避免精度丢失 float profit_rate = (float)amount / cost * 100; printf("You made %.1f%c profit\n", profit_rate, percent); printf("or\n"); printf("%d %c profit\n", amount, dollar); } else if (cost > sell) { amount = cost - sell; float loss_rate = (float)amount / cost * 100; printf("You made %.1f%c loss\n", loss_rate, percent); printf("or\n"); printf("%d %c loss\n", amount, dollar); } else { // 处理成本价等于售价的情况 printf("No profit, no loss\n"); } // 可选:如果运行后窗口直接关闭,添加这行让程序暂停 // getchar(); return 0; }
关键修改点说明
- 用
else if和else覆盖了盈利、亏损、不赚不亏三种所有可能的情况,确保无论输入什么数值,都会进入对应的分支 - 亏损金额改为
cost - sell,保证输出正数 - 改用浮点型计算利润率,避免整数除法导致的精度问题(比如成本价150、盈利50时,整数计算会得到0%,浮点计算能得到准确的33.3%)
- 变量名改为
cost、sell这类有意义的名称,比x、y更易读
内容的提问来源于stack exchange,提问作者Nature Lover
相关产品推荐
相关产品推荐

