I've been studying c++, and I ran into an implicit conversion issue that I don't understand. In this code:
#include <iostream>
using namespace std;
int main(){
int i;
i = 1 / 2 * 2 / 1. * 2. / 4 * 4;
cout << i << endl;
i = 3.5 + 2 + 1.6;
cout << i << endl;
i = 2 + 3.5 + 1.6;
cout << i << endl;
return 0;
}
Ithe outputs are: 0, 7 and 7 respectively.
In the last 2 examples, the compiler is implicitly converting the elements to doubles, so the sum = 7.1, which is then cast to an int to get 7.
Because the 1st example also has doubles, I'd expect all of those elements to be converted to doubles as well, and the sum being 2.0, before being cast to 2, but the result is 0, so it seems the "1/2" is being treated as ints, giving a result of 0. I'm not sure that's what the compiler is doing, but that's what it seems like.
I thought if any element was a double, the compiler would implicitly convert all elements to double. This doesn't happen in the 1st case though. Can someone please explain why the compiler converts these differently? Thanks.