1

there is an expression (as a part of median calculation):

auto iter1 = std::next(first, floor(size/2) - 1 );
double result  = *iter1 + *(iter1 + 1)) / 2;

where the type of the value under iterators is int.

expected result e.g.:

1.5 = (1 + 2 ) / 2

however , in case of values 1 and 2 the result is 1, looks like implicit conversion to int

please explain, what the rule (or my misunderstanding?) is applied here

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
amigo421
  • 2,429
  • 4
  • 26
  • 55

1 Answers1

4

In your second expression double result = *iter1 + *(iter1 + 1)) / 2;: as per operator precedence, the evaluation of *(iter1 + 1)) / 2 is done first; and since the operands of the / operator are both ints, the sub-expression will result in integer division. The result of the integer division is then added to *iter1.

there is an expression (as a part of median calculation):

double result  = *iter1 + *(iter1 + 1)) / 2;

Since the common type of the expression in the right hand side is an int. No conversion is done. Having at least one double will fix you problem. (Also note the parenthesis I added to fit your example).

double result  = (*iter1 + static_cast<double>(*(iter1 + 1))) / 2.0;
Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68