我使用两个不同的变量来除以来自的变量int
and double
。当我使用类似以下内容时,这些工作正常:
int cost
cost = 40;
cost = (cost / 400) * 20 * 2;
为此,该方法工作正常,我得到了正确的结果,即4
,但是当我使用变量时cost
并将其放在标题中,例如:
#define cost 40
int total_cost;
total_cost = (cost / 400) * 20 * 2;
这总是导致0
对我来说,我不知道为什么。即使我使用printf
with %d
or %f
这仍然给了我一个结果0
.
您正在进行整数除法 - 向下舍入。
所以:
cost / 400
返回零,因为cost = 40
and 40 / 400
向下舍入为零。
你应该做的是使用浮点类型,例如double
.
EDIT:
double cost
cost = 40;
cost = (cost / 400) * 20 * 2;
and
#define cost 40
double total_cost;
total_cost = ((double)cost / 400) * 20 * 2;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)