SUMA SPOJ

0

Robie zadanie z suma https://pl.spoj.com/problems/SUMA/

#include <iostream>



using namespace std;

int main() {

	int tab[300];
	int suma = 0;
	for (int i = 0; i < 300; i++) {

		cin >> tab[i];
		suma = suma + (tab[i]);
		cout << suma << endl;

		
	}

lecz nie wiem jak przerwac petle gdy wcisniety zostanie klawisz entera, bo chyba tak to trzeba zrobic?

0

Raczej chodzi o to, żebyś wykrył koniec danych: http://www.cplusplus.com/reference/ios/ios/eof/

1

Inaczej, użyj powyższego, pętla coś w ten deseń:

  while (cin >> n) {
    //TODO
    if (cin.eof())
      break;
  }

Acha i std::vector zamiast tablicy.

4

Tutaj w ogóle nie ma potrzeby używać żadnej tablicy.

Moje stare rozwiązanie zawiera się w kilku linijkach

	int total{}, temp;
	while (std::cin >> temp) {
		total += temp;
		std::cout << total << '\n';
	}

Teraz nawet napisałem bardziej fancy rozwiązanie:

#include <algorithm>
#include <iostream>
#include <iterator>

int main(){
	std::ios::sync_with_stdio(false);
	std::transform(
		std::istream_iterator<int>(std::cin), {},
		std::ostream_iterator<int>(std::cout, "\n"),
		[total = 0](int n) mutable { return total += n; }
	);
}
1
#include <numeric>
#include <iostream>
#include <iterator>

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::partial_sum(
        std::istream_iterator<int>(std::cin), {},
        std::ostream_iterator<int>(std::cout, "\n"));

    return 0;
}

https://godbolt.org/z/Wzqfnx

1

Mi się bardziej podoba krótka wersja:

#include <iostream>
using namespace std;

int main() 
{
    for(int sum=0,current;cin>>current;cout<<(sum+=current)<<endl) {}
    return 0;
}
1

Prześcigacie się w pochwaleniu jak zgrabnie umiecie programować, a ignorujexie że OP i tak nie rozróżni między tymi podejściami

1 użytkowników online, w tym zalogowanych: 0, gości: 1