It is not entirely clear by the condition of the task that they want to do. I ask you to explain the conditions that they want to find there. Condition: in the array A [1..6] find the sum of positive elements that are in the range from -1 to 5 inclusive.

  • Strange task. If you need to add only positive elements, then why the additional condition from -1 to 5? - cy6erGn0m
  • To confuse. - ling
  • It also seemed strange to me. Can you just remove this additional condition or change it to normal? - ArniLand
  • But can the condition A[i] > 0 && A[i] <= 5 ? - alexlz

2 answers 2

  int[] a = new int[6] ; // вводим/получаем/считываем значения // подсчитываем сумму int sum = 0 ; for ( int i = 0 ; i < a.length ; i++ ) { // отсекаем все кроме положительных if ( a[i] > 0 ) { // проверяем попадает ли число в диапазон от [-1 до 5] // нижнюю границу мы уже проверили т.е // разбили диапазон на: [-1; 0] U (1, 5] // поэтому проверяем только правую часть if (a[i] <= 5) { sum = sum + a[i]; } } } 

you have a description of the array at the beginning of the task, and the condition that the numbers (meaning only positive) should fall into the range at the end, it is logical to assume that this requirement applies to them. This is a banal test of your logical thinking, because the programmer’s task is to look for and describe patterns:

  // как НЕ нужно делать if ( a[i] > 0 ) { if ( -1 <= a[i] && a[i] <= 5 ) { sum = sum + a[i] ; } } // как нужно делать if ( a[i] > 0 ) { if ( a[i] <= 5 ) { sum = sum + a[i] ; } } 

    Here is the solution:

     #include "stdafx.h" #include <iostream> using namespace std; double m[6]; double summa; int i, kon; int main() { cout << "Vvedite chisla v diapasone ot -1 do 5" << endl; for (i = 0; i < 6; i++) cin >> m[i]; for (i = 0; i < 6; i++) { if (m[i] > 0) summa = summa + m[i]; } cout << "Summa = " << summa; cin >> kon; return 0; } 
    • 2
      Why windows.h, stdafx.h and math.h? And in general, do not interfere with the students to learn the simplest tasks. If they do not master them themselves, they will never learn anything. - cy6erGn0m
    • You are right, they are not needed. It's just that I copied it from another program. Too lazy to re-connect every time these libraries. (Only here "stdafx.h" is needed, since I wrote in VS) - NikiCh
    • one
      for what was to spread the solution? Would you at least normally edit the code, and then the extra input and variables. It was impossible to simply clarify what is required to find the sum of positive numbers, and it is required to maintain numbers in the range -1 to 5. - ArniLand
    • From the solution, all the answers are immediately visible. - NikiCh
    • Only it hurts the students, too lazy to explain the conditions already. - ArniLand