hi there
just a i think im getting somewhere in c im stuck when this compiles x comes out as 6 it should be 9 can someone please tell me what is going wrong
thanks
#include <stdio.h>
main()
{
int x,y,z;
x = 9;
y = (x=6)/3;
z = x * y + 1 + 2 - 3 * 4;
printf("x = %d, y = %d, z = %d\n", x,y,z);
printf("answer is %d\n", 3 * 17);
// fflush(stdin);
// getchr();
And exactly what are you expecting from this? Unless you know exactly what the order of operations will be, you should use parentheses to clearly define the order.
Consider.. moving strictly from left to right...
x*y = 27
+1 = 28
+2 =30
-3 = 27
*4 = 108
However, running the code and printing it, the result is 18, because C++ does not operate from left to right. Multiply has precidence over add, so it boils down to:
Of course, proper order of operation is multiplication and division first, then addition and subtraction. As lar3ry says, better to use parentheses to remove any ambiguity.
It doesn't "round" y.
y is declared as an int:
int x,y,z;
so it can only be an integer number.
if you want decimals, you need to use data type "float".
jonwhite:
i mean rounded down to 5.0 thats correct?
i dont understand 2/3 = 1 in my mind thats 0.6 what does this get rounded down to?
so not sure what that gets rounded down to ?
I'm guessing that 2 divided 3 is not equal to 1 in your mind it is equal to two thirds.
And then you are assuming that in C that would be one
But it is really zero.
Rounding is not what is happening here.
There is no rounding going on, it is truncation.
Since these are integers the values are integers which have no decimal component
so there is no way to express anything but an integer.
Imagine covering up everything on your calculator to the right of the decimal
point and including the decimal point.
That is what an integer is.
And when calculating integer expressions, the truncation will happen along
every step in the case of multiple divides.