Performing operations between int and double
I have a homework assignment in basic C that asks me to evaluate certain expressions and then check my answers in a program. I can't seem to get any of these answers correctly 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 variables are converted to integer, so it should look something like this:
(4 + 2) / (3-4)
I got -6 as my answer when I do it manually, but when I enter it as code it gives me an answer of 0. Can anyone explain this? Am I doing the wrong order of operations? I just don't understand how the computer gets 0 from this. This is the easiest question in my homework and I have no clue. Please, help!
source to share
Your expression
b+a/c-d
coincides with
b + (a/c) - d
Since both a
and c
are integers, the factor a/c
is computed using integer division. It gives 2/3 = 0
. So you have:
b - d
It is calculated using floating point, since b
and d
are double
. The result is 0.5, which is int
truncated to 0 when the result is assigned .
source to share