Here is the task: In the real array X = (x1, x2, ..., xn) each pair of x [i] and x [j] (i, j = 1, ..., n; i <> j) negative elements convert to positive elements using the formula x [i], x [j]: = sqrt (x [i] * x [j]). Pairs of elements (i, j) should be selected in the order of their sequence in the array X. Here is my intended solution:

void Mass::change(){ //int pos1 = 0; //int pos2 = 0; bool flag = false; for (int i = 0; i < dim; i++) { if (v[i] < 0) { int pos1 = 0; int pos2 = 0; for (int i = 0; i < dim; i++) { if (v[i] < 0) { flag = true; pos1 = i; } break; } for (int i = pos1 + 1; i < dim; i++) { if (v[i] < 0) { if (flag == true) { pos2 = i; v[pos1] = v[pos2] = sqrt(v[pos1] * v[pos2]); } else { flag = true; pos1 = i; } break; } } cout << "\n"; for (int i = 0; i < dim; i++) cout << v[i] << " "; // вывожу измененный массив cout << "\n" << pos1 << pos2; // проверяю запись позиций } } 

This is what gives: enter image description here

  • You have nested loops using the same variable i . And what's the point of doing an unconditional break; at the end of the cycle? - HolyBlackCat
  • Because otherwise the cycle immediately reaches the last element ignoring the rest - Norfo4ik
  • Do you understand that you might as well take the code out of the loop, putting i=0 before the code? In addition, there remains a problem with the same variable for different nested loops ... - HolyBlackCat

1 answer 1

No internal cycles are needed.

 var v = [-9, 17, -16, -104, 19, -26]; var dim = v.length; var sqrt = Math.sqrt; var pos1 = -1; for (var i = 0; i < dim; i++) { if (v[i] < 0) { if (pos1 == -1) { // found first negative pos1 = i; } else { // found second negative v[pos1] = v[i] = sqrt(v[pos1] * v[i]); pos1 = -1; // restart count of negatives } } } console.log(JSON.stringify(v)); 

  • The question is about real elements, which in C ++ (the question mark) corresponds to a double (and not int ), and the initialization list is written in curly brackets. Index pos1 in fact. type int . (And the rest is similar -)) - avp