CS50代码返回值异常:为何调整运算顺序后结果正确?
整数除法导致的计算错误分析
问题现象
第一段代码预期计算(100-percent)/100 * price,但实际返回0.00:
#include<stdio.h> #include<cs50.h> float discount(int prec , float pri); int main (void){ int percent = get_float("enter the present here "); float price = get_float("enter the price "); float function1 = discount(percent , price); printf("the new number is %.2f\n", function1); } float discount(int prec , float pri){ return (100 - prec)/100 * pri ; }
运行输出:
$ make lesson $ ./lesson enter the present here 15 enter the price 100 the new number is 0.00
调整运算顺序后的第二段代码得到正确结果:
#include<stdio.h> #include<cs50.h> float discount(int prec , float pri); int main (void){ int percent = get_float("enter the present here "); float price = get_float("enter the price "); float function1 = discount(percent , price); printf("the new number is %.2f\n", function1); } float discount(int prec , float pri){ return pri * (100 - prec)/100 ; }
运行输出:
$ make lesson $ ./lesson enter the present here 14 enter the price 100 the new number is 86.00
错误原因
问题核心在于C语言的整数除法特性:
- 第一段代码中,
(100 - prec)是整数类型,100也是整数类型,两者执行除法时会触发整数除法——直接舍去小数部分,只保留整数结果。比如输入15时,100-15=85,85/100的整数除法结果为0,再乘以float类型的pri,最终结果就是0.00。 - 第二段代码调整运算顺序后,先执行
pri * (100 - prec):由于pri是float类型,整数(100 - prec)会被自动转换为float参与运算,得到的结果是float类型;后续除以整数100时,100也会被转换为float,执行浮点数除法,最终得到精确的小数结果。
补充解决方式
除了调整运算顺序,也可以通过显式将整数转为float来避免整数除法,比如把100写成100.0:
return (100 - prec)/100.0 * pri ;
此时(100 - prec)会被提升为float类型,执行浮点数除法,结果同样正确。
内容的提问来源于stack exchange,提问作者Mo salah
相关产品推荐
相关产品推荐

