for example i did 5/3 and it gave me 1 even tho it was supposed to say 1.6666666666666666666666 |
In C++, when you divide two integers, the result is an integer. It rounds towards zero, so 5/3 is 1 and (-5)/3 is -1.
An easy mistake to make is to do this:
1 2 3
|
int i1=5;
int i2=3;
double d = i1/i2;
|
You might think that this will result in d=1.666666... but it doesn't. It gives d=1. The reason is that the compiler evaluates the right side of the expression without caring what you will do with it, and as you saw above, integer division results in an integer result. Then the compiler takes that integer result and converts it to a double to assign to d.
To handle this, you just have to cast one of the values to a double. This will force the compiler to promote the other argument to double and do division of doubles:
double d = static_cast<double>(i1)/i2;
It's worth reading and understanding the subtleties of how expressions are evaluated. Read up on precedence and order of evaluation. Precedence tells you where the implicit parentheses go. E.g., that
a+b*c
is evaluated like
a+(b*c)
. In other words, in what order are the
operators executed. Order of evaluation describes the order in which the operands are evaluated. In other words, whether c = a() + b() is like
1 2 3
|
int op1 = a();
int op2 = b();
int c = op1+op2;
|
or
1 2 3
|
int op2 = b();
int op1 = a();
int c = op1+op2;
|
In general, the order of evaluation is undefined - the compiler is free to do it however it wants. So you have to write code that won't care. Precedence on the other hand is generally very well defined.