Reputation: 27133
Sorry for this simple question, but I can't solve it...
There is an example:
int a[10] = {6, 7.8, 8.0, -6, -5.7, 5, 5.7};
std::cout << a[6 % 8 / 4 + 21 % 9];
In response I get -5, but I don't understand why.
Upvotes: 1
Views: 112
Reputation: 3930
6 % 8 / 4 => (6%8) / 4 => 6 / 4 => (int)1.5 => 1
(6/4 is int -- num and denom are ints)
21 % 9 => 3
1 + 3 == 4
a[4] == (int)(-5.7) == 5
a
is an int
array and so the numbers there are int's and not floats.
index 4 is chosen because of C++ operator precedence
Upvotes: 2
Reputation: 3825
http://en.cppreference.com/w/cpp/language/operator_precedence Operators have their priority so in this case: 6 % 8 / 4 + 21 % 9 = (((6%8)/4)+(21%9))=(6/4)+(3)=4
a[0]=6,
a[1]=(int)7.8 = 7, (correct me if i'm wrong)
a[2] = (int)8.0 = 8,
a[3] = -6,
a[4] = (int)-5.7 = -5,
a[5] = 5,
a[6] = (int)5.7 = 5
So element with index 4 it's -5.7 casted to integer gives -5 (the rest is just cut off)
Upvotes: 3
Reputation: 4589
because your array is a integer array.
you should use at first
float a[10]
Upvotes: 7