While code does not do the correct condition

2

I need to create a code that reads only a double and registers in two variables the "lowest so far" and the "largest so far", I can even successfully complete a cycle but after that it prints any value that I enter.

I tried some ways to do a function, go back to looping, but it would get faulty.

while(cin>>num1){
    cout << "maior ate agora " << num1 << endl;
    cin >> num2;
    if(num2 > num1)
        cout << "maior ate agora " << num2;
    else
        cout << "maior ate agora " << num1;
}
    
asked by anonymous 07.11.2015 / 19:00

2 answers

1

The code has some problems and the biggest one is that the comparison is always being made with the first number and not with the largest so far. Another serious problem is not having a way out. I've changed so that a negative number manages the output. You can change it to another criterion if you want to accept negatives.

#include <iostream>
using namespace std;

int main() {
    int maior = 0, numero = 0;
    while (numero >= 0) {
        cin >> numero;
        if(numero > maior) {
            maior = numero;
            cout << "maior ate agora " << maior << endl;
        }
    }
    return 0;
}

See running on ideone .

    
07.11.2015 / 19:13
1

The comparison is being made in the wrong way because it always compares to the first. Change your while :

while (num1 >= 0) {
   cin >> num1;
   if(num1 > maior) {
      maior = num1;
      cout << "maior ate agora " << maior << endl;
   }
}
    
30.11.2016 / 14:04