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.

James T
  • 3,292
  • 8
  • 40
  • 70
Ali
  • 9,997
  • 20
  • 70
  • 105
  • 2
    If you use that exact formula, with ints, i'm pretty sure it *won't* "work fine". The problem is that the integer division gives you 0, which will happen regardless of the final type. `cost` (or perhaps the 400) should be a `double`, or the formula simplified or operations rearranged. For example, `(cost / 400) * 20 * 2` == `(cost / 400) * 40` == `cost * 40 / 400` == `cost / 10`, unless you *intend* to rely on integer division. (Doesn't seem to be the case, considering how much trouble it's giving you.) – cHao Oct 11 '11 at 00:27
  • Possible duplicate of [Division result is always zero](https://stackoverflow.com/questions/2345902/division-result-is-always-zero) – phuclv Jun 17 '18 at 12:49

2 Answers2

7

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;
Mysticial
  • 464,885
  • 45
  • 335
  • 332
  • what will be the the solution since my assignment needed to put the value in header only – Ali Oct 11 '11 at 00:14
  • Declare your variables as type `double`. So `double cost` and `double total_cost`. Furthermore, you need to cast your values to `double` before the division. – Mysticial Oct 11 '11 at 00:16
  • Or alternatively just cast them to double in the computation to enforce floating point operations: `((double)cost / 400.0) * 20.0 * 2.0`. – Christian Rau Oct 11 '11 at 00:17
  • 1
    @Ali The define would just be `#define cost 40.0`. – Christian Rau Oct 11 '11 at 00:19
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:

total_cost = cost * 20 * 2 / 400;

Multiplication happens first, division last, giving you:

40 * 20 * 2 / 400 = 800 * 2 / 400 = 1600 / 400 = 4
Tim
  • 8,912
  • 3
  • 39
  • 57