每当使用除法时,C 程序中的计算结果总是为 0

发布于 2024-12-09 10:00:42 字数 470 浏览 0 评论 0原文

我使用两个不同的变量来除以 intdouble 中的变量。当我使用以下内容时,这些工作正常:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

桃酥萝莉 2024-12-16 10:00:42

您正在进行整数除法 - 向下舍入。

因此:

cost / 400

返回零,因为 cost = 4040 / 400 向下舍入为零。

你应该做的是使用像double这样的浮点类型。

编辑:

double cost
cost = 40;
cost = (cost / 400) * 20 * 2;

#define cost 40
double total_cost;
total_cost = ((double)cost / 400) * 20 * 2;

You are doing integer division - which rounds down.

Therefore:

cost / 400

is returning zero because cost = 40 and 40 / 400 rounds down to zero.

What you should do is use a floating-point type like 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;
摘星┃星的人 2024-12-16 10:00:42

运算顺序和整数除法。

整数除法总是截断。从数学上讲,40/400 = .1 - 但这不是整数。剩下的被扔掉,留下:40 / 400 = 0

在您的示例中,运算顺序意味着首先完成除法。由于乘法和除法的顺序并不重要(从数学上来说),请尝试更改顺序:

total_cost = cost * 20 * 2 / 400;

首先发生乘法,最后发生除法,给出:

40 * 20 * 2 / 400 = 800 * 2 / 400 = 1600 / 400 = 4

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:

total_cost = cost * 20 * 2 / 400;

Multiplication happens first, division last, giving you:

40 * 20 * 2 / 400 = 800 * 2 / 400 = 1600 / 400 = 4
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文