C语言薪资计算代码中salary介于1000至1500的条件不生效问题咨询
问题原因说明
- 分支顺序逻辑错误:你代码中第三个判断分支
else if (salary<3000)已经覆盖了所有薪资小于3000的情况,所有符合该条件的输入都会直接进入这个分支执行,后续判断1000~1500区间的分支永远没有触发机会。 - 区间判断语法错误:C语言不支持
1500>salary>1000这类连续比较写法。该表达式实际运算逻辑是先计算1500>salary得到布尔值(成立返回1,不成立返回0),再用这个0或1的结果和1000比较,永远无法得到“salary处于1000到1500之间”的判断结果,正确写法应为salary > 1000 && salary < 1500。
修复后的代码示例
float salary; printf("Hello !\n"); printf("This program calculates the net salary for an employee in a company. \n"); printf("please input the salary for the employee : \n"); scanf("%f", &salary); if (salary>=5000){ printf("The salary for the employee is %f" ,salary-( salary*15/100)); } else if (salary>=3000){ printf("The salary for the employee is %f", salary-salary*10/100); } else if (salary>=1500){ printf("The salary for the employee is %f", salary-salary*5/100); } else if (salary>1000 && salary<1500){ printf("The salary for the employee is %f", salary+200); } else{ printf("The salary of the employee is less than 1000"); }
内容的提问来源于stack exchange,提问作者Aboubker Khaled
相关产品推荐
相关产品推荐

