问题
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
.
回答1:
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;
回答2:
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
来源:https://stackoverflow.com/questions/7720078/calculation-in-c-program-always-results-in-0-whenever-using-division