3

I have a homework assignment in basic C that is asking me to calculate certain expressions and then check my answers in a program. I can't seem to get any of these answers correct by my own calculations...

They want me to solve math problems using these variables:

int a = 2;
double b = 4.7;
int c = 3;
double d = 4.2;

Here's an example question:

int answer1 = b+a/c-d; 

I understand that since it has an int operand then all the variables convert to an integer, so it should look something like this I think:

(4+2)/(3-4)

I got -6 as my answer when doing it by hand, but when I input it as code it gives me an answer of 0. Can anyone explain this? Am I doing the order of operations wrong? I simply don't understand how the computer gets 0 out of that. This is the easiest question in my homework and I don't have a clue. Please help!

jlest
  • 85
  • 2
  • 3
  • 6
  • 4
    Firstly, "I understand that since it has an int operand then all the variables convert to an integer" - that is already not even remotely true. Secondly, you C expression `b+a/c-d` has no braces in it. Your mathematical expression `(4+2)/(3-4)` has braces in it. Why the difference? – AnT stands with Russia Sep 02 '14 at 21:14
  • Okay, I feel stupid now. So is the final answer the only thing that gets converted to a integer? Looks like I should have taken a math class beforehand for review haha. Thanks for your help! – jlest Sep 02 '14 at 21:19

2 Answers2

5

Your expression

b+a/c-d

is the same as

b + (a/c) - d

Since both a and c are integers, then the quotient a/c is computed using integer division. That gives 2/3 = 0. So then you have:

b - d

This is calculated using floating point since b and d are double. The result is 0.5, which when assigned to the result int, is truncated to 0.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • Ahhhh! Now I see where I went wrong. I guess I needed some review in basic order of operations. Thank you for providing clarity! – jlest Sep 02 '14 at 21:22
1

Your orders of operations is a bit off:

int answer1 = b+(a/c)-d; 

int tmp1 = a/c; ---> 2/3 --> 0
int answer1 = 4.7 + 0 - 4.2 ----> 0.5 --> 0

http://www.cplusplus.com/doc/tutorial/typecasting/

tinkertime
  • 2,972
  • 4
  • 30
  • 45