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.

2
  • 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.) Commented Oct 11, 2011 at 0:27
  • Possible duplicate of Division result is always zero Commented Jun 17, 2018 at 12:49

2 Answers 2

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; 
Sign up to request clarification or add additional context in comments.

4 Comments

what will be the the solution since my assignment needed to put the value in header only
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.
Or alternatively just cast them to double in the computation to enforce floating point operations: ((double)cost / 400.0) * 20.0 * 2.0.
@Ali The define would just be #define cost 40.0.
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.