每当使用除法时,C 程序中的计算结果总是为 0
我使用两个不同的变量来除以 int
和 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
与 %d
或 %f
一起使用,这仍然会给出 0
的结果。
I'm using two different variable to divide in the calculation with the variable from int
and double
. These work fine when I use something like:
int cost
cost = 40;
cost = (cost / 400) * 20 * 2;
For this the method works fine and I get the right result which is 4
, but when I use the variable cost
and put it in the header instead, like:
#define cost 40
int total_cost;
total_cost = (cost / 400) * 20 * 2;
this always results in 0
for me and I don't know why. Even if I use printf
with %d
or %f
this still gives me a result of 0
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在进行整数除法 - 向下舍入。
因此:
返回零,因为
cost = 40
和40 / 400
向下舍入为零。你应该做的是使用像
double
这样的浮点类型。编辑:
和
You are doing integer division - which rounds down.
Therefore:
is returning zero because
cost = 40
and40 / 400
rounds down to zero.What you should do is use a floating-point type like
double
.EDIT:
and
运算顺序和整数除法。
整数除法总是截断。从数学上讲,40/400 = .1 - 但这不是整数。剩下的被扔掉,留下:
40 / 400 = 0
。在您的示例中,运算顺序意味着首先完成除法。由于乘法和除法的顺序并不重要(从数学上来说),请尝试更改顺序:
首先发生乘法,最后发生除法,给出:
Order of operations, and Integer Division.
Integer Division always truncates. Mathematically, 40/400 = .1 - but that's not an integer. The remainder is thrown away, leaving you with:
40 / 400 = 0
.Order of operations means that the division is done first, in your example. Since the order of multiplication and division doesn't matter too much (mathematically speaking), try changing the order:
Multiplication happens first, division last, giving you: