C语言if-else逻辑作业问题:收入计税程序错误排查
你的C语言代码中的错误分析
scanf参数传递错误:
scanf("%f", income);这里必须传递变量的地址&income。scanf需要通过指针来修改外部变量的值,直接传income会把变量当前值当作内存地址使用,大概率导致程序崩溃或内存访问异常。条件边界值未覆盖:你的分支逻辑漏掉了
income == 2.5、income == 5.0、income == 10.0这些情况,当输入这些值时,程序不会进入任何一个分支,没有输出结果。需要调整条件让区间连续覆盖所有可能值,比如把区间改成>2.5 && <=5.0这类形式。冗余变量未使用:你声明了
float tax但全程没有赋值或调用,属于多余代码,可以直接删除;如果需要计算实际税额,也可以根据税率给tax赋值后再输出。
修正后的代码示例
#include<stdio.h> int main () { float income; printf("Kindly note down your income here\n"); scanf("%f", &income); // 修正:传递变量地址 if (income > 2.5 && income <= 5.0) { printf("You have to pay 5%% tax because your income is %.2f\n", income); } else if (income > 5.0 && income <= 10.0) { printf("You have to pay 20%% tax because your income is %.2f\n", income); } else if (income > 10.0) { printf("You have to pay 30%% tax because your income is %.2f\n", income); } else // 覆盖所有income <= 2.5的情况,包括等于2.5 { printf("You have to pay no tax because your income is %.2f\n", income); } return 0; }
内容的提问来源于stack exchange,提问作者Vishva Modh
相关产品推荐
相关产品推荐

