每当使用除法运算时,C程序中的计算结果始终为0 [英] calculation in C program always results in 0 whenever using division

查看:52
本文介绍了每当使用除法运算时,C程序中的计算结果始终为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用两个不同的变量在计算中使用变量 int double 进行除法.当我使用类似的东西时,这些效果很好:

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;

为此,该方法可以正常工作,并且得到正确的结果,即 4 ,但是当我使用变量 cost 并将其放在标头中时,例如:

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;

这对我来说总是导致 0 而我不知道为什么.即使我将 printf %d %f 一起使用,这仍然给我 0 的结果.

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.

推荐答案

您正在做整数除法-四舍五入.

You are doing integer division - which rounds down.

因此:

cost / 400

返回零,因为 cost = 40 40/400 向下舍入为零.

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

您应该做的是使用像 double 这样的浮点类型.

What you should do is use a floating-point type like double.

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

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

这篇关于每当使用除法运算时,C程序中的计算结果始终为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆