Enter a sequence of numbers, the number of which is not known in advance. A sign of the end of the input sequence of numbers is the input in a row given in the source data of numbers with the same signs. Print the sum of the last in a sequence of negative numbers entered in a row.

Input Example: 3 1, -2, -3,4, -5, -6,7,8,9 Expected result: -11

I made an array input before entering a certain number of elements in a row with the same characters, but I cannot figure out how to calculate the sum of the last negative elements entered in a row if the array ends with not positive negative numbers entered, but positive.

#include "stdafx.h" #include <iostream> #include <cmath> using namespace std; int i,n,polozh,predel,otric,kolvo,j,sum,endf,w; int a[30]; int _tmain(int argc, _TCHAR* argv[]) { cout << "Vvedite kolichestvo elementov" << endl; cin >> predel; polozh=0; j = 0; otric=0; i=0; endf = 0; w = 1; while (endf==0) { cin >> a[i]; if ((a[i] > 0)) { sum = 0; otric=0; polozh++; if (polozh >= predel) { endf = 1; } } if ((a[i] < 0)) { polozh=0; otric++; sum = sum + a[i]; if (otric >= predel) { endf = 1; } } cout << " POLOZH = " << polozh << endl; cout << " OTRIC = " << otric << endl; cout << "SUMMA = " << sum<<endl; i++; kolvo++; } for (i=0;i<=kolvo-1;i++) { cout << a[i] << " "; } system("pause"); return 0; } 
  • And you are on the positive elements of the amount does not reset. And expose some variable-flag, which was a positive number. When you meet a negative number and this flag is set - reset the amount and reset the flag - Mike

1 answer 1

Set check flag

  int _tmain(int argc, _TCHAR* argv[]) { cout << "Vvedite kolichestvo elementov" << endl; cin >> predel; polozh=0; j = 0; otric=0; i=0; endf = 0; w = 2; while (endf==0) { cin >> a[i]; if ((a[i] > 0)) { if(w == 2) w = 1; otric=0; polozh++; if (polozh >= predel) { endf = 1; } } if ((a[i] < 0)) { if(w == 1){ w = 2; sum = 0; } polozh=0; otric++; sum = sum + a[i]; if (otric >= predel) { endf = 1; } } cout << " POLOZH = " << polozh << endl; cout << " OTRIC = " << otric << endl; cout << "SUMMA = " << sum<<endl; i++; kolvo++; } for (i=0;i<=kolvo-1;i++) { cout << a[i] << " "; } system("pause"); return 0; } 
  • Subtracting a negative number gives an addition with a positive. Amount is always an addition - Mike