Major / Minor / Sum in C ++ using 'for'

0

I want to make a program that reads 5 numbers and tell me the largest number, the smallest number and the sum of the numbers, in C ++ using the for loop.

I tried and did so:

#include <iostream>
using namespace std;

int main()
{
  int n, i, h, l, s;

  cout<<"Digite 5 numeros:\n";

  for (i=0; i<5; i++)
  {
      cin>>n;
      s+=n;

      if (n>l)
      {
          n=h;
      }
      else
      {
          n=l;
      }
  }

  cout<<"O maior numero e "<<h<<", o menor e "<<l<<" e a soma e "<<s<<".\n";

  return 0;

}
    
asked by anonymous 08.04.2017 / 13:19

2 answers

1
#include <iostream>
using namespace std;

int main(){
    int n, i, h, l, s = 0; // Inicializar a soma "s" em zero
    cout << "Digite 5 números:\n";

    for(i=0; i<5; i++){
        cin >> n;
        s+=n;
        if (i==0) {l=n; h=n;} // Inicializar os valores de "l" e "h" no primeiro loop
        if (n<l) { l=n; }
        if (n>h) { h=n; }
    }
}

With this code, the sum is started at zero, and the highest and lowest values are initialized with the first value, and starting from that we begin to make comparisons.

    
28.04.2017 / 00:10
0

1 - Variables are not receiving initial value. 2 - Instead of n > l, make n> h. 3 - When n is greater than the highest current value, you say h = n, not the opposite. Try to do this:

#include <iostream>
using namespace std;

int main() {
    int n, i, high=0, low=1e10, s=0;

    cout<<"Digite 5 numeros:\n";
    for (i=0; i<5; i++)
    {
        cin>>n;
        s+=n;
        if (n>high)
            high=n;
        if (n<low)
            low=n;
    }
    cout<<"O maior numero e "<<high<<", o menor e "<<low<<" e a soma e "<<s<<".\n";

    return 0;
}
    
24.04.2017 / 10:50